Gimuser39
Gimuser39

Reputation: 97

How to call setState() inside task of workmanager plugin

I use workmanager plugin to execute a background task of triggering notification around every 15 minitues.

void main() async{
  // needs to be initialized before using workmanager package

  WidgetsFlutterBinding.ensureInitialized();
  await NotificationApi.init();


  // initialize Workmanager with the function which you want to invoke after any periodic time
  Workmanager().initialize(callbackDispatcher);

  // Periodic task registration
  Workmanager().registerPeriodicTask(
    "2",
    // use the same task name used in callbackDispatcher function for identifying the task
    // Each task must have a unique name if you want to add multiple tasks;
    "myTask",
    // When no frequency is provided the default 15 minutes is set.
    // Minimum frequency is 15 min.
    // Android will automatically change your frequency to 15 min if you have configured a lower frequency than 15 minutes.
    frequency: Duration(minutes: 15), // change duration according to your needs
  );

  runApp(MyApp());
  

}

Here is the top level function callbackdispatcher() used by workmanager on every 15 minutes

 void callbackDispatcher() {

    Workmanager().executeTask((task, inputdata) async {
      switch (task) {
        case "myTask":
          final notificationPlugin = FlutterLocalNotificationsPlugin();
          var platformChannelSpecifics = new NotificationDetails(
              android: AndroidNotificationDetails(
                  'your channel id',
                  'your channel name',
                  'your channel description',
                  importance: Importance.max,
                  priority: Priority.high,
                additionalFlags: Int32List.fromList(<int>[4]),
              ),
              iOS: IOSNotificationDetails()
          );
          await notificationPlugin.show(0, "Hello", "This is nottification", platformChannelSpecifics);
       /*  setState(() {
      
      cStatus = false;
      
    });*/
          break;

        case Workmanager.iOSBackgroundTask:
          print("iOS background fetch delegate ran");
          break;
      }

      //Return true when the task executed successfully or not
      return Future.value(true);
    });
  }

Here the notification is succesfully called every 15 minutees. But I cannot call setState function to rebuild the widget. Is there any way to call setstate inside top level function. Because I need to rebuild a widget from background task.

Upvotes: 1

Views: 437

Answers (1)

Shahood ul Hassan
Shahood ul Hassan

Reputation: 799

It is not possible to call setState() from inside a WorkManager task because these tasks run in a background thread while setState() works with the main thread. Also, WorkManager is designed to work even when the app is closed, so in that case too, setState() won't work. For updating the UI, you may think about persisting the task updates to SharedPreferences or a database and listening to those updates in your widgets in order to update the UI.

Upvotes: 0

Related Questions