Flutter周期性通知重复显示同个字符串问题求助
问题根源
你现在用的periodicallyShow方法是固定内容重复推送,点击按钮时只生成了一次randomName,之后系统就一直重复推送这个固定字符串,不会自动重新生成随机值。setState没用是因为periodicallyShow的内容在调用时就已经固定,后续更新变量不会影响已经安排好的通知。
解决方案
核心思路是放弃periodicallyShow,改用定时任务+单次通知的组合,每次触发定时任务时重新生成随机名称,再发送新的通知。
步骤1:修改NotificationService的通知方法
把periodicallyShow换成单次通知的show方法:
Future<void> showNotification(int id, String title, String body) async { await flutterLocalNotificationsPlugin.show( id, title, body, const NotificationDetails( android: AndroidNotificationDetails('main_channel', 'Main Channel', channelDescription: "ashwin", importance: Importance.max, priority: Priority.max), iOS: DarwinNotificationDetails( sound: 'default.wav', presentAlert: true, presentBadge: true, presentSound: true, ), ), androidAllowWhileIdle: true, ); }
步骤2:在页面中实现定时任务
管理一个Timer实例,点击按钮后启动定时任务,每次触发时生成新的随机名称并发送通知:
// 页面类中定义变量 Timer? notificationTimer; final random = Random(); final List<String> names = ["张三", "李四", "王五", "赵六"]; // 你的名称列表 // 修改按钮点击逻辑 onPressed: () { showToast(); // 先取消之前的定时任务(防止重复启动) notificationTimer?.cancel(); // 立即发送第一次随机通知 _sendRandomNotification(); // 启动定时任务,每隔一分钟执行一次 notificationTimer = Timer.periodic(const Duration(minutes: 1), (timer) { _sendRandomNotification(); }); }, // 新增发送随机通知的方法 void _sendRandomNotification() { String randomName = names[random.nextInt(names.length)]; NotificationService().showNotification(1, 'Hello', randomName); } // 页面销毁时取消定时任务,避免内存泄漏 @override void dispose() { notificationTimer?.cancel(); super.dispose(); }
补充说明
- 如果需要通知不被覆盖,可以每次使用不同的id(比如用时间戳或者递增数字)。
- 如果要实现应用后台运行时也能推送,需要用到后台任务插件(比如
workmanager),因为前台Timer在应用退到后台一段时间后会被系统暂停。
内容的提问来源于stack exchange,提问作者Marian
相关产品推荐
相关产品推荐

