Skip to content

Comprehensive Guide to Integrating Real-time Device Location Tracking in Flutter Using `flutter_background_geolocation

In this tutorial, we’ll cover the integration of the flutter_background_geolocation plugin for real-time location tracking in your Flutter application. This guide will be split into three main parts for better comprehension:

  1. Installation – Setting up the necessary dependencies.
  2. Configuration – Configuring the plugin for both Android and iOS platforms.
  3. Implementation and Testing – Implementing the functionality in your Flutter app and testing it.

Part 1: Installation

Adding Dependencies

To get started, open your pubspec.yaml file and add the flutter_background_geolocation dependency:

dependencies:
  flutter:
    sdk: flutter
  flutter_background_geolocation: ^4.15.5

Run flutter pub get to fetch the new dependencies.

Android Setup

  1. Add Maven Repositories

    Modify your android/build.gradle file to include the necessary Maven repositories:

    allprojects {
       repositories {
           google()
           mavenCentral()
           maven { url 'https://developer.huawei.com/repo/' }
           maven { url "${project(':flutter_background_geolocation').projectDir}/libs" }
           maven { url "${project(':background_fetch').projectDir}/libs" }
       }
    }
  2. Modify AndroidManifest

    Edit your android/app/src/main/AndroidManifest.xml to include the necessary permissions and metadata:

    
    
       
    
           
           
           
       
    
  3. Add to build.gradle

    Modify android/app/build.gradle:

    android {
       compileSdkVersion 33
       defaultConfig {
           minSdkVersion 21
           targetSdkVersion 33
       }
       buildTypes {
           release {
               minifyEnabled true
               shrinkResources false
               proguardFiles "${project(':flutter_background_geolocation').projectDir}/proguard-rules.pro"
           }
       }
    }
    
    apply from: "${project(':flutter_background_geolocation').projectDir}/background_geolocation.gradle"

iOS Setup

  1. Background Modes and Permissions

    Open your ios/Runner.xcworkspace in Xcode. Enable the background modes under Signing & Capabilities:

    • Location updates
    • Background fetch
    • (Optional) Audio

    Then, add the necessary permissions to your Info.plist:

    
       NSMotionUsageDescription
       Motion usage description
       NSLocationWhenInUseUsageDescription
       When in use description
       NSLocationAlwaysAndWhenInUseUsageDescription
       Always/When in use description
       UIBackgroundModes
       
           fetch
           location
       
    
  2. Privacy Manifest

    Apple requires a Privacy Manifest for sensitive APIs. Create or edit PrivacyInfo.xcprivacy:

    
    
       NSPrivacyAccessedAPITypes
       
           
               NSPrivacyAccessedAPIType
               NSPrivacyAccessedAPICategoryUserDefaults
               NSPrivacyAccessedAPITypeReasons
               
                   CA92.1
               
           
           
       
    
    

Part 2: Configuration

Basic Configuration

First, import the flutter_background_geolocation package and configure it:

import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();

    // Set up event listeners
    bg.BackgroundGeolocation.onLocation((bg.Location location) {
      print('[location] - $location');
    });

    bg.BackgroundGeolocation.onMotionChange((bg.Location location) {
      print('[motionchange] - $location');
    });

    bg.BackgroundGeolocation.onProviderChange((bg.ProviderChangeEvent event) {
      print('[providerchange] - $event');
    });

    // Configure the plugin
    bg.BackgroundGeolocation.ready(bg.Config(
      desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10.0,
      stopOnTerminate: false,
      startOnBoot: true,
      debug: true,
      logLevel: bg.Config.LOG_LEVEL_VERBOSE,
    )).then((bg.State state) {
      if (!state.enabled) {
        bg.BackgroundGeolocation.start();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Background Geolocation'),
      ),
      body: Center(
        child: Text('Tracking in progress...'),
      ),
    );
  }
}

Advanced Configuration (Optional)

You can customize the plugin behavior further by modifying the configuration settings:

bg.BackgroundGeolocation.ready(bg.Config(
  desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
  distanceFilter: 50.0,
  stopOnTerminate: false,
  startOnBoot: true,
  debug: false,
  logLevel: bg.Config.LOG_LEVEL_OFF,
  locationAuthorizationRequest: 'Always',
  stopTimeout: 5,
  // Additional configurations...
)).then((bg.State state) {
  if (!state.enabled) {
    bg.BackgroundGeolocation.start();
  }
});

Part 3: Implementation and Testing

Running the Application

  1. Start the application in debug mode to verify that the plugin is working as expected.

  2. Check the console logs for location updates, motion changes, and provider changes.

  3. Test background functionality by minimizing the app and verifying that location updates are still being logged.

Testing in Release Mode

Ensure that all configurations are correct and that you have included the necessary licenses for release builds. Run the app in release mode to verify that everything works seamlessly.

Debugging

Use the following methods to assist in debugging:

  • Check logs for any errors or warnings.
  • Verify permissions on both Android and iOS.
  • Ensure background modes are properly enabled.
  • Check for conflicts in AndroidManifest or build.gradle files.

Conclusion

By following this comprehensive guide, you should have a robust implementation of real-time device location tracking in your Flutter application. This setup ensures that your app can track location even when running in the background, providing a seamless experience for users.

If you encounter any issues or need further customization, refer to the official documentation of the flutter_background_geolocation plugin or reach out to the community for support.

Leave a Reply

Your email address will not be published. Required fields are marked *