Optimize Your App’s Navigation with Device GPS Location in Flutter

The ability to retrieve a mobile application’s GPS position is one of its key features. We will go through how to activate a device’s GPS location in a Flutter application in this tutorial.

Add the Location package

We must include the location package in our application in order to use the device’s GPS position in Flutter. A collection of classes and methods for interacting with the device’s location services are offered by the location package.

dependencies:
  location: ^5.0.0

Android

Using the enableBackgroundMode({bool enable}) API is required before accessing location in the background and granting the required permissions in order to use location background mode on Android. You ought to grant your applications the necessary permissions.

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

Keep in mind that in order to use the background location consistently, the user must approve location permission. The location permission dialogue prompt does not have the Android 11 option to always accept. It must be explicitly enabled by the user via the app’s settings. The user should be informed of this through a different user interface (UI) that takes them to the operating system-managed location settings of the application. You can learn more about that subject on the developer website for Android.

IOS

And to use it in iOS, you have to add this permission in Info.plist :

// This is probably the only one you need. Background location is supported
// by this -- the caveat is that a blue badge is shown in the status bar
// when the app is using location service while in the background.
NSLocationWhenInUseUsageDescription

// Deprecated, use NSLocationAlwaysAndWhenInUseUsageDescription instead.
NSLocationAlwaysUsageDescription

// Use this very carefully. This key is required only if your iOS app
// uses APIs that access the user’s location information at all times,
// even if the app isn't running.
NSLocationAlwaysAndWhenInUseUsageDescription

To receive location when application is in background, to Info.plist you have to add property list key :

UIBackgroundModes

with string value:

location

Web

Nothing to do, the plugin works directly out of box.

macOS

Ensure that the application is properly “sandboxed” and that the location is enabled. You can do this in Xcode with the following steps:

  1. In the project navigator, click on your application’s target. This should bring up a view with tabs such as “General”, “Capabilities”, “Resource Tags”, etc.
  2. Click on the “Capabilities” tab. This will give you a list of items such as “App Groups”, “App Sandbox”, and so on. Each item will have an “On/Off” button.
  3. Turn on the “App Sandbox” item and press the “>” button on the left to show the sandbox stuff.
  4. In the “App Data” section, select “Location”.

Add this permission in Info.plist :

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

Usage

Then you just have to import the package with

import 'package:location/location.dart';

Request Permission

We must first ask the user for permission before we can access the GPS location of the device. The permission might be accepted or denied by the user. If denial occurs, we must graciously manage the mistake. We can utilise the location package’s requestPermission() method to ask for permission.

import 'package:location/location.dart';

class LocationService {
  Location location = Location();

  Future<bool> requestPermission() async {
    final permission = await location.requestPermission();
    return permission == PermissionStatus.granted;
  }
}
Dart

Get the current location

The getLocation() function of the Location class can be used to obtain the device’s current location once permission has been granted. The location’s latitude, longitude, altitude, and accuracy are all contained in the LocationData object that is returned by the procedure.

import 'package:location/location.dart';

class LocationService {
  Location location = Location();

  Future<bool> requestPermission() async {
    final permission = await location.requestPermission();
    return permission == PermissionStatus.granted;
  }

  Future<LocationData> getCurrentLocation() async {
    final locationData = await location.getLocation();
    return locationData;
  }
}
Dart

Check if the GPS is enabled

We must make sure the device’s GPS is turned on before we can ask for the location. We must ask the user to enable the GPS if it isn’t already. The Location class’s serviceEnabled() function can be used to determine whether the GPS is activated. In the event that the method returns false, we can ask the user to enable the GPS by using the Location class’s requestService() method. To see if the GPS is enabled, use this sample code:

import 'package:location/location.dart';

class LocationService {
  Location location = Location();

  Future<bool> requestPermission() async {
    final permission = await location.requestPermission();
    return permission == PermissionStatus.granted;
  }

  Future<LocationData> getCurrentLocation() async {
    final serviceEnabled = await location.serviceEnabled();
    if (!serviceEnabled) {
      final result = await location.requestService();
        if (result == true) {
          print('Service has been enabled');
        } else {
             throw Exception('GPS service not enabled');
          }
       }
       final locationData = await location.getLocation();
      return locationData;
    }
 }
Dart

You can also get continuous callbacks when your position is changing:

location.onLocationChanged.listen((LocationData currentLocation) {
  // Use current location
});
Dart

To receive location when application is in background you have to enable it:

location.enableBackgroundMode(enable: true)
Dart

On Android, a foreground notification is displayed with information that location service is running in the background.

location.changeNotificationOptions(
        channelName: "my channel",
        description: "description channel",
        onTapBringToFront: false,
        title: "Demo App",
        subtitle: "Checking location on foregound",
        iconName: "",
        color: Colors.red
      );
Dart

On iOS, while the app is in the background and gets the location, the blue system bar notifies users about updates. Tapping on this bar moves the User back to the app.