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

Flutter中使用awesome_notifications实现通知点击跳转页面报错求助

解决Awesome Notifications点击跳转指定页面问题

核心方案:全局导航键+动作流监听覆盖全场景

要实现通知点击跳转,关键是确保能获取到导航上下文,同时覆盖应用前台/后台/未启动三种场景的通知动作处理。

步骤1:定义全局导航键

在项目入口文件中定义全局导航键,用于在监听回调中获取导航上下文:

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

将该键绑定到MaterialApp:

class MyApp extends StatelessWidget {
  final GlobalKey<NavigatorState> navigatorKey;

  const MyApp({super.key, required this.navigatorKey});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      title: 'Flutter Demo',
      home: const HomeScreen(),
    );
  }
}

步骤2:初始化并监听通知动作

在main函数中完成Awesome Notifications的初始化,同时处理两种场景的通知点击:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化通知渠道配置
  await AwesomeNotifications().initialize(
    'resource://drawable/app_icon', // 替换为你的通知图标路径
    [
      NotificationChannel(
        channelKey: 'basic_channel',
        channelName: '基础通知',
        channelDescription: '测试用通知渠道',
        defaultColor: Colors.blue,
        importance: NotificationImportance.High,
        channelShowBadge: true,
      )
    ]
  );

  // 监听前台/后台状态下的通知点击
  AwesomeNotifications().actionStream.listen((receivedAction) {
    final context = navigatorKey.currentContext;
    if (context != null) {
      // 根据payload标识跳转对应页面
      final targetScreen = receivedAction.payload?['screen'];
      switch(targetScreen) {
        case 'detail':
          Navigator.push(context, MaterialPageRoute(builder: (_) => const DetailScreen()));
          break;
        case 'settings':
          Navigator.push(context, MaterialPageRoute(builder: (_) => const SettingsScreen()));
          break;
        default:
          Navigator.push(context, MaterialPageRoute(builder: (_) => const HomeScreen()));
      }
    }
  });

  // 处理应用未启动时,点击通知打开app的场景
  final initialAction = await AwesomeNotifications().getInitialNotificationAction();
  if (initialAction != null) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final context = navigatorKey.currentContext;
      if (context != null) {
        final targetScreen = initialAction.payload?['screen'];
        // 复用跳转逻辑
        switch(targetScreen) {
          case 'detail':
            Navigator.push(context, MaterialPageRoute(builder: (_) => const DetailScreen()));
            break;
          // 其他页面分支
        }
      }
    });
  }

  runApp(MyApp(navigatorKey: navigatorKey));
}

步骤3:发送带标识的通知

发送通知时通过payload携带页面标识,实现动态跳转:

Future<void> sendTestNotification() async {
  await AwesomeNotifications().createNotification(
    content: NotificationContent(
      id: DateTime.now().millisecond,
      channelKey: 'basic_channel',
      title: '测试通知',
      body: '点击跳转到详情页',
      payload: {'screen': 'detail'}, // 携带目标页面标识
    ),
  );
}

常见错误排查

  • 未设置全局导航键:直接在监听中使用context会触发空指针,必须通过navigatorKey获取上下文。
  • 未处理初始动作:应用未启动时点击通知,actionStream不会触发,必须调用getInitialNotificationAction处理。
  • iOS配置缺失:iOS需在Info.plist中添加后台模式权限,确保通知动作能被捕获:
    <key>UIBackgroundModes</key>
    <array>
      <string>remote-notification</string>
    </array>
    

内容的提问来源于stack exchange,提问作者abdellah driouich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:25:28