Hello everyone, in this post I'm going to teach you how you can easily implement a simple location service that gives you the user longitude and latitude using flutter. it's very simple and very easy and you can do it within 10 minutes.
Get started
first of all, you have to create a new Flutter project, you can call whatever you want, then you will need to add the geolocator package. to do this just open your pubspec.yaml file and inside dependencies add this line:
geolocator: ^5.1.5
before we start coding, we need to set up a few things. First, check your android SDK by going to
android > app > build.Gradle file and check your SDK version, it should be at least 28
android {
compileSdkVersion 28
Now open your AndroidManifest.xml file and add the uses permission to allow the app to access the device location service.
Now that everything is set up let's start coding
The Code
so let's go to our main.dart file and let's create a simple layout that will contain a button and a text
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LocationApp(),
);
}
}
class LocationApp extends StatefulWidget {
@override
_LocationAppState createState() => _LocationAppState();
}
class _LocationAppState extends State<LocationApp> {
var _locationMessage = "";
void _getCurrentLocation() async {
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location service"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("${_locationMessage}"),
Center(
child: RaisedButton(
onPressed: () {
_getCurrentLocation();
},
child: Text("get location"),
),
),
],
),
);
}
}
As you can see we created a variable where we will store our location data and a Void function where we will get the data. now let's code the getCurrentLocation function
void _getCurrentLocation() async {
final postion = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
final lastPosition = await Geolocator().getLastKnownPosition();
print("last Position = ${lastPosition}");
setState(() {
_locationMessage = "${postion.latitude} , ${postion.longitude}";
});
}
GeoLocator is very simple to use because we have all the function built-in and we don't need any extra coding. if you want to know more about the package you can check the Documentation
I hope that you liked this post, if you faced any problem just comment bellow and we will respond as fast as we can
How to Get The User Location In Flutter
Reviewed by Medics
on
September 26, 2020
Rating:
Nice
ReplyDelete