首页 > 解决方案 > 如何在 workmanager 插件的任务中调用 setState()

问题描述

我使用 workmanager 插件执行每 15 分钟触发通知的后台任务。

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());
  

}

这是 workmanager 每 15 分钟使用的顶级函数 callbackdispatcher()

 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);
    });
  }

此处每 15 分钟成功调用一次通知。但是我不能调用 setState 函数来重建小部件。有没有办法在顶级函数中调用 setstate 。因为我需要从后台任务重建一个小部件。

标签: flutterflutter-widgetflutter-workmanager

解决方案


推荐阅读