How to implement GPS Status change listener in flutter

Viewed 1377

I was in a FLUTTER project that's related to OLA, UBER, so i need a stream function(like flutter GeoLocatior().isLocationServiceEnabled()) that notifies when user turns off location.

2 Answers

You can use the Location Permissions package to achieve this.location_permissions

Stream <bool> locationEventStream;
@override
void initState() {
 locationEventStream = LocationPermissions().serviceStatus.map((s) => s == ServiceStatus.enabled ? true : false);
}

@override
Widget build(BuildContext context) {
  return StreamBuilder < bool > (
   stream: locationEventStream,
   builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.active && snapshot.hasData) {
     if (snapshort.data) {
      //GPS on
     } else {
      //GPS off
     }
    }
   }
  }

Geolocator package has this functionality. It can be used same as below:

StreamSubscription<ServiceStatus> serviceStatusStream = Geolocator.getServiceStatusStream().listen(
    (ServiceStatus status) {
        print(status);
    });
Related