How to Get User's Location in Flutter with Geolocator Package

How to Get User's Location in Flutter with Geolocator Package

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:

  1. Create a project on Android Studio. I'll give it the name user_location

  2. 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),
                   ),
                 ],
               ),
             ));
       }
     }
    
  3. 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 running flutter pub get.

  4. 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 to 33 in the "android/app/build.gradle" file

        android {
          compileSdkVersion 33
      
          ...
        }
      
    • We need to add a permission rule to AndroidManifest.xml to copy these lines to the AndroidManifest.xml file which located in android/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';
      
  5. 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)

  6. 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 location

     Center(
                   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.