Run method works with widgets from background task in Flutter Dart

37 Views Asked by At

Context. Flutter 3.19.0 y Dart 3.3.0 • DevTools 2.31.1

What am I doing. I'm testing how background tasks work with the flutter_background_service package. I managed to successfully run the example application (this)

In summary, the background task in this example does something very simple: it gets the device name and the current datetime and sends them to the front, that is, to the screen that the user sees.

What I want to do. I have created the following method:

  void myMethod(List<File> imagesList, StreamController<int> wallpaperStreamController, int currentImage) {
    if (imagesList.isNotEmpty) {
      wallpaperStreamController.add(currentImage);
      currentImage = (currentImage + 1) % imagesList.length;
      const Duration intervaloDeRotacion = Duration(seconds: 10);
      Timer.periodic(intervaloDeRotacion, (Timer timer) {
        if (widgetIsMounted) {
          wallpaperStreamController.add(currentImage);
          currentImage = (currentImage + 1) % imagesList.length;
        }
        else {
          timer.cancel();
        }
      });
    }
  }

My method changes the device wallpaper using the flutter_wallpaper_manager package. My method works fine if I run it in the foreground, pressing a button:

  ElevatedButton(
   onPressed: () {
      myController.myMethod(
       myController.imagesList,
       myController.wallpaperStreamController,
       myController.currentImage,
    )},
   child: Text('Press here'),
  )

In order for my method to run in the background, it naively occurred to me to put my method inside the onStart method. But it doesn't work: When I press the button to start the task in the background, the push notification is shown with the text "AWESOME SERVICE Initializing", and that's it, it doesn't even execute my method (because it doesn't change the wallpaper on my phone), nor does the screen show the datetime coming from the task in the background.

  @pragma('vm:entry-point')
  void onStart(ServiceInstance service) async {
   //...

   MyController myController = Get.put(MyController());
   myController.myMethod(
    myController.imagesList,
    myController.wallpaperStreamController,
    myController.currentImage,
   );

   //...
  }

Why is this happening? I think this is happening because I am trying to execute a method that belongs to a widget controller from the context of a background service, and I understand that this is not possible, since the widget controller It is not available in the background service context.

What alternatives do I have to achieve my goal?

0

There are 0 best solutions below