If you want to obtain the user's location in Flutter, you can utilize the Geolocator
package. This package offers a simple method to retrieve the current user's location. Additionally, it provides other details such as the most recent known location, ongoing location updates, and calculation of the distance (in meters) between two sets of geo coordinates. You can acquire it from the pub.dev website.
So Let's get Started:
Create a project on Android Studio. I'll give it the name
user_location
In the
main.dart
file let's replace the content of_MyHomePageState
with a Column widget that contains a Button widget to get the user's location and a Text widget to display the result. it will be like this:class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text('Current Location: '), SizedBox( height: 25, ), FloatingActionButton( onPressed: () {}, tooltip: 'Increment', child: Icon(Icons.add), ), ], ), )); } }
Now we need to install the
geolocator package
either by running this command in the terminal:flutter pub add geolocator
or by adding this line
dependencies: geolocator: ^10.0.1
to the dependencies in the
pubspec.yaml
file then runningflutter pub get
.In order to be able to use the package we need to configure the Android and iOS files. For IOS you can read the instructions here. For now, we will make the changes to be able to work on Android devices. here are the steps:
Add the following to your "gradle.properties" file if they do not exist:
android.useAndroidX=true android.enableJetifier=true
We need to set the
compileSdkVersion
to33
in the"android/app/build.gradle"
fileandroid { compileSdkVersion 33 ... }
We need to add a permission rule to
AndroidManifest.xml
to copy these lines to theAndroidManifest.xml
file which located inandroid/app/src/main
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
After these steps, we will be able to use the package when we import it to the file we want by writing this line in the
main.dart
import 'package:geolocator/geolocator.dart';
Now, we will utilize the package in the
main.dart
file. We have a button that, when clicked by the user, triggers a function to retrieve the user's location. The code for this functionality will be as follows:// a variable to save the current position of the user Position? _position; void _getCurrentLocation() async { Position position = await _determinePosition(); setState(() { _position = position; }); } /// we get the function from the docs of the package Future<Position> _determinePosition() async { LocationPermission permission; permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { // Permissions are denied, next time you could try // requesting permissions again (this is also where // Android's shouldShowRequestPermissionRationale // returned true. According to Android guidelines // your App should show an explanatory UI now. return Future.error('Location permissions are denied'); } } if (permission == LocationPermission.deniedForever) { // Permissions are denied forever, handle appropriately. return Future.error( 'Location permissions are permanently denied, we cannot request permissions.'); } // When we reach here, permissions are granted and we can // continue accessing the position of the device. return await Geolocator.getCurrentPosition(); }
If we run the app using
flutter run
and click on the button here's what we get this image![result](https://github.com/rashaabdulrazzak/userLocationFlutter/blob/main/images/res.JPG)
To display the result in the text in the
main.dart
:After we defined the
_position
We will check if it exists we will show it or we will show there is no locationCenter( child: _position != null ? Text('Current Location: ' + _position.toString()) : Text('No location data'), ),
Then we rerun the app again and after we allow the app to get our location we can see the location on the screen as this image
At this stage, we have successfully obtained the user's location and presented it on the screen. The package offers additional functionalities that you can explore. Here is the Git link for the final outcome. If you have any questions, please leave them in the comments.