Get Current User Location in Flutter

Getting the user location in Flutter is made very simple by the Geolocator plugin. According to the docs, this plugin uses the native services for Android and iOS to get the location and to geocode it.

A Flutter geolocation plugin which provides easy access to the platform specific location services (FusedLocationProviderClient or if not available the LocationManager on Android and CLLocationManager on iOS).

In this example, we will use this plugin to get the location of the user on the start of the app, and display the address on the screen.

 

Step 1: Add the dependency

Start off by adding the dependency to the pubspec.yaml file.

geolocator: ^5.3.1

Run pub get.

 

Step 2: Configure the platforms

Android Project

One. Make sure your project is using AndroidX.

If you’re not sure, check gradle.properties file in the android folder. You should see a line like this

android.useAndroidX=true

If your project is not using AndroidX, check AndroidX migration.

Two. Modify AndroidManifest.xml file to add the necessary permissions.

It can be found inside <your-project-root-directory>/android/app/src/main/ folder

Add the following two lines, just above the <application> tag.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

iOS Project

Modify the Info.plist file to add the permissions.

It can be found inside <your-project-root-directory>/ios/Runner/ folder

Add the following keys to the file. If you’re confused, add them at the end, just above the closing two tags </dict></plist>

You can modify the description.

   <key>NSLocationWhenInUseUsageDescription</key>
   <string>This app needs access to location when open.</string>

   <key>NSLocationAlwaysUsageDescription</key>
   <string>This app needs access to location when in the background.</string>

   <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
   <string>This app needs access to location when open and in the background.</string>

That’s all for the configuration, now we can go back to our Flutter project and write the code.

 

Get the user’s location

In your screen’s dart file, import the library.

import 'package:geolocator/geolocator.dart';

Create variables for storing the position and the address, in the state class.

Position _currentPosition;
String _currentAddress;

Instantiate the geolocator class.

final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;

Finally, get the location

_getCurrentLocation() {
  geolocator
      .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
      .then((Position position) {
    setState(() {
      _currentPosition = position;
    });
    _getAddressFromLatLng();
  }).catchError((e) {
    print(e);
  });
}

We have got the coordinates of the location. But we cannot display that on our screen! So we shall write the above-referenced function to get the address.

Get address from the coordinates

_getAddressFromLatLng() async {
  try {
    List<Placemark> p = await geolocator.placemarkFromCoordinates(
        _currentPosition.latitude, _currentPosition.longitude);
    Placemark place = p[0];
    setState(() {
      _currentAddress =
      "${place.locality}, ${place.postalCode}, ${place.country}";
    });
  } catch (e) {
    print(e);
  }
}

 

Display address on the screen

Wherever you want to display the address.

if (_currentPosition != null && _currentAddress != null) Text(_currentAddress),

 

Full Code Example

This is an example of the code in a screen, with some formatting and styling.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';

class DashboardScreen extends StatefulWidget {
  @override
  _DashboardState createState() => _DashboardState();
}

class _DashboardState extends State<DashboardScreen> {
  final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
  Position _currentPosition;
  String _currentAddress;

  @override
  void initState() {
    super.initState();
    _getCurrentLocation();
  }

  _getCurrentLocation() {
    geolocator
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
      });

      _getAddressFromLatLng();
    }).catchError((e) {
      print(e);
    });
  }

  _getAddressFromLatLng() async {
    try {
      List<Placemark> p = await geolocator.placemarkFromCoordinates(
          _currentPosition.latitude, _currentPosition.longitude);

      Placemark place = p[0];

      setState(() {
        _currentAddress =
            "${place.locality}, ${place.postalCode}, ${place.country}";
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DASHBOARD"),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
                decoration: BoxDecoration(
                  color: Theme.of(context).canvasColor,
                ),
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Icon(Icons.location_on),
                        SizedBox(
                          width: 8,
                        ),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                'Location',
                                style: Theme.of(context).textTheme.caption,
                              ),
                              if (_currentPosition != null &&
                                  _currentAddress != null)
                                Text(_currentAddress,
                                    style:
                                        Theme.of(context).textTheme.bodyText2),
                            ],
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                      ],
                    ),
                  ],
                ))
          ],
        ),
      ),
    );
  }
}

This will produce the following result:

 

 


Also published on Medium.

By |2020-05-19T23:27:44+00:00May 19th, 2020|Categories: Flutter|Tags: |0 Comments

Leave A Comment