flutterdartgeolocationlocationbackground-process

How to Flutter App run continuously fetch data after every 10 sec in background when app is closed/terminated or screen off


How to Flutter App run continuously in the background when the app is closed/terminated. I have to fetch the location continuously when the app is terminated/closed or the screen is locked.


Solution

  • Try work manager

    https://pub.dev/packages/workmanager

    Create a root level method and use that method to create a background process.

    void callbackDispatcher() {
      Workmanager().executeTask((task, inputData) {
        print("Native called background task: $backgroundTask"); //simpleTask will be emitted here.
        return Future.value(true);
      });
    }
    
    void main() {
      Workmanager().initialize(
        callbackDispatcher, // The top level function, aka callbackDispatcher
        isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
      );
      Workmanager().registerOneOffTask("task-identifier", "simpleTask");
      runApp(MyApp());
    }