You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter点击通知跳转仅后台生效?应用被杀死时点击仅打开首页

问题原因

FirebaseMessaging.onMessageOpenedApp 仅在应用后台存活时,用户点击通知唤醒应用才会触发。当应用被完全杀死后,点击通知冷启动应用时该监听不会生效,你需要额外处理冷启动场景下的初始消息获取。
另外你当前代码未在MaterialApp中注册/productsScreen路由,也会导致跳转失败。

修复步骤

1. 补全路由配置

修改MyApp组件,为MaterialApp注册对应的命名路由:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => MyHomePage(title: 'Flutter Demo Home Page'),
        // 替换为你实际的产品页组件
        '/productsScreen': (context) => ProductsScreen(),
      },
    );
  }
}

2. 新增冷启动通知处理逻辑

在_MyHomePageState的initState方法中,追加getInitialMessage调用,处理应用被杀死后点击通知启动的场景:

@override
void initState() {
  super.initState();
  subscribeToTopic();

  // 处理应用冷启动时的通知点击事件
  FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
    if (message != null) {
      // 可根据message.data内的自定义参数判断跳转逻辑,此处按你的需求固定跳产品页
      Navigator.pushNamed(context, '/productsScreen');
    }
  });

  // 原有前台接收通知逻辑
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print('onMessage data is ${message.data}');
    print('onMessage notification is ${message.notification}');

    RemoteNotification? notification = message.notification;
    AndroidNotification? android = message.notification?.android;
    if (notification != null && android != null) {
      flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              channel.description,
              color: Colors.blue,
              playSound: true,
              icon: '@mipmap/ic_launcher',
            ),
          ));
    }
  });

  // 原有后台存活状态下的通知点击逻辑
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    print('A new onMessageOpenedApp event was published!');
    Navigator.pushNamed(context, '/productsScreen');
  });
}
注意事项

如果需要根据不同通知跳转到不同页面,只需要在getInitialMessage和onMessageOpenedApp的回调中读取message.data内的自定义参数,做对应路由判断即可。发送通知时请同时携带notification和data字段,避免参数丢失。

内容的提问来源于stack exchange,提问作者Omar Abdelazeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 13:30:02