Search code examples
flutterdartbackground-service

How to run code even if the app is closed


Can an flutter app still run code even if the app is closed? I am trying to build an application that notifies a user even if the app is closed. Hoping for answers. TIA.


Solution

  • By default you would have to integrate your background service on a platform specific way.

    But I found this package that handles the native integration mostly for you: flutter_background_service.

    final service = FlutterBackgroundService();
      await service.configure(
        androidConfiguration: AndroidConfiguration(
          // this will executed when app is in foreground or background in separated isolate
          onStart: onStart,
    
          // auto start service
          autoStart: true,
          isForegroundMode: true,
        ),
        iosConfiguration: IosConfiguration(
          // auto start service
          autoStart: true,
    
          // this will executed when app is in foreground in separated isolate
          onForeground: onStart,
    
          // you have to enable background fetch capability on xcode project
          onBackground: onIosBackground,
        ),
      );
      service.startService();
    

    Code snippet taken from the package example here.

    How to add the package to your project:

    1. Open your pubspec.yaml file
    2. Add flutter_background_service: ^2.4.3 to your dependency section
    3. Run flutter pub get