Flutter中如何配置本地定时通知的点击跳转指定页面功能?
解决FlutterLocalNotifications定时通知点击跳转问题
要让本地定时通知点击后跳转指定页面,需要完成三个关键步骤:
- 给FlutterLocalNotificationsPlugin设置通知点击回调
- 调用定时通知时传入标识跳转目标的payload参数
- 在回调中解析payload并执行页面跳转
具体修改如下:
- 初始化时添加点击回调
在initNotifications方法中,初始化FlutterLocalNotificationsPlugin时传入onSelectNotification回调,处理点击事件:
// 替换原有的notificationsPlugin.initialize调用 await notificationsPlugin.initialize( initializationSettings, onSelectNotification: (String? payload) async { if (payload != null) { final Map<String, dynamic> data = jsonDecode(payload); // 复用Firebase的跳转逻辑,根据参数跳转到对应页面 if (data['invoice_id'] != null) { Future.delayed(const Duration(milliseconds: 1250)).then((_) { navKey.currentState?.push( MaterialPageRoute( builder: (context) => WareHouseSalesDetails( id: int.parse(data['id']), invoiceId: '${data['invoice_id']}', ), ), ); }); } else if (data['moving_id'] != null) { Future.delayed(const Duration(milliseconds: 1250)).then((_) { navKey.currentState?.push( MaterialPageRoute( builder: (context) => MovingDetailsPage( id: int.parse(data['id']), movingId: '${data['moving_id']}', ), ), ); }); } } }, );
- 定时通知传入payload参数
修改scheduleNotification方法,将payLoad参数传入zonedSchedule:
Future scheduleNotification( {int id = 0, String? title, String? body, String? payLoad, required DateTime scheduledNotificationDateTime}) async { return notificationsPlugin.zonedSchedule( id, title, body, tz.TZDateTime.from( scheduledNotificationDateTime, tz.local, ), const NotificationDetails( iOS: DarwinNotificationDetails( presentAlert: true, presentBadge: true, presentSound: true, ), android: AndroidNotificationDetails( 'your channel id', 'your channel name', importance: Importance.max, priority: Priority.high, icon: '@mipmap/ic_launcher', showWhen: false)), androidAllowWhileIdle: true, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime, payload: payLoad); // 新增此行,传入payload }
- 调用定时通知时构造payload
调用scheduleNotification时,将跳转所需参数转为JSON字符串作为payload传入:
// 示例:生成跳转到WareHouseSalesDetails的payload final invoicePayload = jsonEncode({ 'id': '456', 'invoice_id': 'INV-20240501', }); await scheduleNotification( title: '待处理销售单', body: '请及时处理编号为INV-20240501的销售订单', payLoad: invoicePayload, scheduledNotificationDateTime: DateTime.now().add(const Duration(minutes: 10)), );
注意事项
- 确保
navKey是全局导航键,且已绑定到MaterialApp的navigatorKey属性 - 延迟跳转是为了确保应用从后台恢复后导航栈已初始化,避免
currentState为空 - 需在项目中导入
dart:convert包用于JSON编解码
内容的提问来源于stack exchange,提问作者st4tic
相关产品推荐
相关产品推荐

