How to cancel geolocation listener in Flutter

You can copy and adopt this source code example to your flutter project easily without issues.

Add this code to your pubspec.yaml file

geolocator: ^5.0.0
 permission_handler: ^3.0.1
 google_maps_flutter: ^0.5.19

Create a cancel_geolocation_listener.dart file (use any name of your choice) and add this code:

 import 'dart:async';

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:permission_handler/permission_handler.dart';

class CancelGeoListener extends StatefulWidget {
  @override
  _CancelGeoListenerState createState() => _CancelGeoListenerState();
}

class _CancelGeoListenerState extends State<CancelGeoListener> {
  Completer<GoogleMapController> _controller = Completer();
  static GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  static LatLng latLng;
  static StreamSubscription _getPosSub;

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

@override
void dispose(){
  _getPosSub?.cancel();
  super.dispose();
}

   Future<void> getLocation() async {
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.location);
    if (permission == PermissionStatus.denied) {
      await PermissionHandler()
          .requestPermissions([PermissionGroup.locationAlways]);
    }

    var geolocator = Geolocator();
    _getPosSub = geolocator.getPositionStream(LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10)).listen((pos){
      return pos;
    });

    GeolocationStatus geolocationStatus =
        await geolocator.checkGeolocationPermissionStatus();
    switch (geolocationStatus) {
      case GeolocationStatus.denied:
        print('denied');
        break;
      case GeolocationStatus.disabled:
      case GeolocationStatus.restricted:
        print('restricted');
        break;
      case GeolocationStatus.unknown:
        print('unknown');
        break;
      case GeolocationStatus.granted:
        await Geolocator()
            .getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
            .then((Position _position) {
          if (_position != null) {
            setState((){
            latLng = LatLng(_position.latitude, _position.longitude,);
            });
          }
        });
        break;
    }
  }

  void _onCancelGeoListener(){
    _getPosSub?.cancel();
  _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Geolocator Listner Canceled"),));

  }


  void _onMapCreated(GoogleMapController controller) {
    _controller.complete(controller);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text('Cancel Geolocation Listener'),
          backgroundColor: Colors.red,
        ),
        body: Stack(
          children: <Widget>[
            GoogleMap(
              onMapCreated: _onMapCreated,
              myLocationEnabled: true,
              initialCameraPosition: CameraPosition(
                target: latLng,
                zoom: 11.0,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                alignment: Alignment.topRight,
                child: Column(
                  children: <Widget> [
                    
                    FloatingActionButton(
                      onPressed: _onCancelGeoListener,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.green,
                      child: const Icon(Icons.add_location, size: 36.0),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

In your main.dart file (main entry point of the app), add this:

import 'package:inducesmile/cancel_geolocation_listener.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new CancelGeoListener(),
    );
  }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment