Flutter中应用关闭时点击本地通知跳转指定页面的方法
解决flutter_local_notifications冷启动点击通知跳转指定页面问题
调度通知时携带路由标识
调用show方法时,通过payload字段传入目标页面的唯一标识(比如'page2'),方便后续点击通知时判断跳转目标:await flutterLocalNotificationsPlugin.show( 0, '通知标题', '通知内容', const NotificationDetails( android: AndroidNotificationDetails( 'channel_id', 'channel_name', channelDescription: 'channel_desc', importance: Importance.max, priority: Priority.high, ), ), payload: 'page2', );处理冷启动场景的通知回调
应用完全关闭后点击通知属于冷启动,需要在main函数初始化插件后,调用getInitialNotification()获取启动时的通知数据,以此决定初始路由:void main() async { WidgetsFlutterBinding.ensureInitialized(); // 初始化通知插件 const AndroidInitializationSettings androidInit = AndroidInitializationSettings('@mipmap/ic_launcher'); const InitializationSettings initSettings = InitializationSettings(android: androidInit); await flutterLocalNotificationsPlugin.initialize(initSettings, onDidReceiveNotificationResponse: (NotificationResponse resp) { // 处理应用在前台/后台时的通知点击 if (resp.payload == 'page2' && navigatorKey.currentContext != null) { Navigator.push( navigatorKey.currentContext!, MaterialPageRoute(builder: (_) => const Page2()), ); } }); // 处理冷启动时的通知触发逻辑 final NotificationResponse? initialNotify = await flutterLocalNotificationsPlugin.getInitialNotification(); String initialRoute = '/'; if (initialNotify?.payload == 'page2') { initialRoute = '/page2'; } runApp(MyApp(initialRoute: initialRoute)); }配置App的路由规则
注册全局导航键(避免后台跳转时context为空),并在MaterialApp中设置初始路由和页面映射:// 全局导航键 final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); class MyApp extends StatelessWidget { final String initialRoute; const MyApp({super.key, required this.initialRoute}); @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: navigatorKey, title: 'Demo', initialRoute: initialRoute, routes: { '/': (_) => const HomePage(), '/page2': (_) => const Page2(), }, ); } }注意事项
- 需提前创建
Page2组件,并在routes中完成路由注册。 - 若使用Router 2.0,需在路由解析逻辑中处理
initialNotify的payload,调整初始路由配置。 - Android端需确保通知渠道配置正确,否则通知可能无法正常触发回调。
- 需提前创建
内容的提问来源于stack exchange,提问作者Ye Ah
相关产品推荐
相关产品推荐

