Dhaval Chaudhari
Dhaval Chaudhari

Reputation: 595

How to set Background Location update In my Flutter App also if App is Closed?

I want to add background location service functionality to my Flutter App.

I want to get location updates at specific time intervals, I have to send location updates latitude and longitude every N minutes so how I can do This either if the app is closed or open or in the background?

I need to send location update details to call the API. So help me how can I do this and what package should I use?

Upvotes: 1

Views: 2820

Answers (1)

Md. Kamrul Amin
Md. Kamrul Amin

Reputation: 2435

Create a service in your app. You can use the following code for location service.

import 'package:location/location.dart';
class LocationService {
  UserLocation _currentLocation;
  var location = Location();

  //One off location
  Future<UserLocation> getLocation() async {
    try {
      var userLocation = await location.getLocation();
      _currentLocation = UserLocation(
        latitude: userLocation.latitude,
        longitude: userLocation.longitude,
      );
    } on Exception catch (e) {
      print('Could not get location: ${e.toString()}');
    }
    return _currentLocation;
  }

  //Stream that emits all user location updates to you
  StreamController<UserLocation> _locationController =
  StreamController<UserLocation>();
  Stream<UserLocation> get locationStream => _locationController.stream;
  LocationService() {
    // Request permission to use location
    location.requestPermission().then((granted) {
      if (granted) {
        // If granted listen to the onLocationChanged stream and emit over our controller
        location.onLocationChanged().listen((locationData) {
          if (locationData != null) {
            _locationController.add(UserLocation(
              latitude: locationData.latitude,
              longitude: locationData.longitude,
            ));
          }
        });
      }
    });
  }
}

The user location model:

class UserLocation {
  final double latitude;
  final double longitude;
  final double heading;
  UserLocation({required this.heading, required this.latitude, required this.longitude});
}

Then in your page/view init Function, start a timer and update location to your location API or Firebase whichever you are using.

Timer? locationUpdateTimer;

    locationUpdateTimer = Timer.periodic(const Duration(seconds: 60), (Timer t) {
      updateLocationToServer();
    });

Remember to dispose timer if you are not using it.

This will update location every 60 seconds when the app is running or in background. To update location when the app is terminated is a bit complex but there is a package which will awake your app every 15seconds. You can go through the documentation on how to achieve this from the following link:

https://pub.dev/packages/background_fetch

Upvotes: 1

Related Questions