gps_service_plugin 0.0.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 46

Background location-tracking module for iOS and Android.

Installing the Plugin #

đź“‚ pubspec.yaml:

Note: See Versions for latest available version.

dependencies: flutter_background_geolocation: '^1.3.2'

Setup Guides #

Android #

It's required to request the ACCESS_FINE_LOCATION permission in AndroidManifest.xml:

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

Also add the following class in the same directory as MainActivity.java and name it Application.java:

public class Application extends FlutterApplication 
                         implements PluginRegistrantCallback {
  @Override
  public void onCreate() {
    super.onCreate();
    GeofencingService.setPluginRegistrant(this);
  }

  @Override
  public void registerWith(PluginRegistry registry) {
    GeneratedPluginRegistrant.registerWith(registry);
  }
}

The purpose of extending FlutterApplication is to set a reference to the application’s plugin registrant within GeofencingService. This is needed to register the application’s plugins with the geofencing plugin’s background isolate, which makes it possible to use other plugins in the context of that isolate.

Finally, set the following field in AndroidManifest.xml to use the new Application instead of the default FlutterApplication:

<application
android:name=".Application"
…

iOS #

Requesting the relevant permissions on iOS requires some simple modifications to Info.plist in the ios directory of the application. First, add the following lines to request background location updates:

<dict>
…
  <key>UIRequiredDeviceCapabilities</key>
  <array>
    <string>location-services</string>
    <string>gps</string>
    <string>armv7</string>
  </array>
  <key>UIBackgroundModes</key>
  <array>
    <string>location</string>
  </array>
…
</dict>

Then set the NSLocation description messages:

<dict>
…
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>YOUR DESCRIPTION HERE</string>
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>YOUR DESCRIPTION HERE</string>
…
</dict>

These descriptions are shown to the user when the application requests access to their location. If they’re not provided, geofencing registration will fail silently!

import UIKit
import Flutter
import gps_service_plugin

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    
    // Register the plugins with the AppDelegate
    registerPlugins(self)
    
    // Set registerPlugins as a callback within GeofencingPlugin. This allows
    // for the Geofencing plugin to register the plugins with the background
    // FlutterEngine instance created to handle events. If this step is skipped,
    // other plugins will not work in the geofencing callbacks!
    SwiftGpsServicePlugin.setPluginRegistrantCallback(registerPlugins)
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

func registerPlugins(_ registry: FlutterPluginRegistry) {
    GeneratedPluginRegistrant.register(with: registry)
}

Finally, set a reference to the application’s plugin registrant within SwiftGpsServicePlugin from the application’s AppDelegate. This is needed to register the application’s plugins with the geofencing plugin’s background isolate, which makes it possible to use other plugins in the context of that isolate.

Dart #

First of all initialize the plugin in initState with static callback function:

  static _onLocation({Position pos, String msg}) async {
    print('pos: $pos, msg: $msg');
  }
  
  @override
  void initState() {
    GpsManager.initialize(FirebaseHelper.onLocation);
    super.initState();
  }

And don't forget to dispose it:

  @override
  void dispose() {
    GpsManager.dispose();
    super.dispose();
  }

Then you can start and stop location tracking:

  void _startLocationTracking() async {
    final isTrackingLocation = await GpsManager.isTreckingLocation();
    if (!isTrackingLocation) {
      GpsManager.startListeningLocation();
    }
  }

  void _stopLocationTracking() async {
    final isTrackingLocation = await GpsManager.isTreckingLocation();
    if (isTrackingLocation) {
      GpsManager.stopListeningLocation();
    }
  }

0.0.1 #

  • TODO: Describe initial release.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:gps_service_plugin/gps_manager.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _switchOn = false;

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

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    print('Initializing...');
    GpsManager.initialize(callback);
    print('Initialization done');
    final isTreckingLocation = await GpsManager.isTreckingLocation();

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    
    setState(() {
	    _switchOn = isTreckingLocation;
    });
  }

  static void callback({Position pos, String msg}) async {
    print('Callback, pos: ${pos?.toString()}');
    print('Callback, lat: ${pos?.lat}, lon: ${pos?.lon}, msg: $msg');
  }

  @override
  void dispose() {
    GpsManager.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(left: 16, right: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                	Text("is trecking location:"),
                  Switch(
                    value: _switchOn,
                    onChanged: (value) {
                      if (value) {
                        GpsManager.startListeningLocation();
                      } else {
                        GpsManager.stopListeningLocation();
                      }
                      setState(() => _switchOn = value);
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  gps_service_plugin: ^0.0.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:gps_service_plugin/callback_dispatcher.dart';
import 'package:gps_service_plugin/generated/i18n.dart';
import 'package:gps_service_plugin/gps_manager.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
11
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
50
Overall:
Weighted score of the above. [more]
46
Learn more about scoring.

We analyzed this package on Jun 5, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.2
  • pana: 0.13.8-dev
  • Flutter: 1.17.1

Health suggestions

Format lib/callback_dispatcher.dart.

Run flutter format to format lib/callback_dispatcher.dart.

Format lib/generated/i18n.dart.

Run flutter format to format lib/generated/i18n.dart.

Format lib/gps_manager.dart.

Run flutter format to format lib/gps_manager.dart.

Maintenance issues and suggestions

Homepage URL doesn't exist. (-20 points)

At the time of the analysis the homepage field https://github.com/eliesystems/flutter_gps_service_plugin.git was unreachable.

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test