flutter - 如何在 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 。因为我需要从后台任务重建一个小部件。
解决方案
推荐阅读
- c# - 查找字符串中最后一次出现的数字,并按该值拆分字符串
- python-3.x - Python 在不知道需要多少实例的情况下,使用各种参数实时运行同一个函数多次
- c# - AcceptTcpClient() 后应用无响应
- javascript - 如何在角度 10 中获取 json 响应数组中的数组?
- arrays - UDP 消息包含奇数字符
- ruby-on-rails - 将 Searchkick 限制应用于搜索查询
- java - 使用迭代器将每个数组元素返回 2 次
- pytorch - Torch:Nccl 可用但未使用(?)
- python - 从元组列表中的值生成组合列表
- haskell - 如何在 Haskell 中编写等式函数