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

Flutter中如何通过FCM传递参数实现指定页面跳转?

实现FCM通知跳转时传递userID参数

步骤1:修改Cloud Function代码,在payload中加入userID参数

更新云函数的payload部分,在data字段中添加userId,或者将路径与参数拼接,方便Flutter端解析:

var payload = {
  "notification": {
    "title": "Booking alert",
    "body": `Your equipment has been booked for ${booking_time} hours`,
  },
  "data":{
    "click_action": "FLUTTER_NOTIFICATION_CLICK",
    // 直接拼接带参数的路由路径
    "path": `/myBookingScreen?userId=${userId}`,
    // 可选:单独保留userId字段,用于更灵活的解析
    "userId": userId
  },
};

步骤2:修改Flutter代码,解析参数并跳转

根据云函数的配置,调整Flutter端的通知点击处理逻辑,解析出userId并传递到目标页面:

flutterLocalNotificationsPlugin.initialize(initializationSettings,
  onDidReceiveNotificationResponse: (response) async {
    if (response.payload != null) {
      print(response.payload.toString());
      // 解析路径和参数
      final uri = Uri.parse(response.payload!);
      final userId = uri.queryParameters['userId'];
      // 跳转到目标页面,传递userId作为参数
      navigatorKey.currentState!.pushNamed(
        uri.path,
        arguments: userId,
      );
    }
  });

如果需要更灵活的参数传递,也可以在云函数中把参数打包成JSON字符串:

"data":{
  "click_action": "FLUTTER_NOTIFICATION_CLICK",
  "payload": JSON.stringify({
    "path": "/myBookingScreen",
    "userId": userId
  })
}

对应的Flutter解析代码(需导入dart:convert):

import 'dart:convert';

flutterLocalNotificationsPlugin.initialize(initializationSettings,
  onDidReceiveNotificationResponse: (response) async {
    if (response.payload != null) {
      final Map<String, dynamic> data = jsonDecode(response.payload!);
      final String path = data['path'];
      final String userId = data['userId'];
      // 跳转并传参
      navigatorKey.currentState!.pushNamed(
        path,
        arguments: userId,
      );
    }
  });

步骤3:配置目标页面接收参数

确保myBookingScreen页面能接收传递的userId参数:

// 路由配置
MaterialApp(
  navigatorKey: navigatorKey,
  routes: {
    '/myBookingScreen': (context) => MyBookingScreen(
          userId: ModalRoute.of(context)?.settings.arguments as String,
        ),
  },
);

// MyBookingScreen页面示例
class MyBookingScreen extends StatelessWidget {
  final String userId;
  const MyBookingScreen({super.key, required this.userId});

  @override
  Widget build(BuildContext context) {
    // 使用userId进行业务逻辑处理
    return Scaffold(
      appBar: AppBar(title: const Text('我的预订')),
      body: Center(child: Text('用户ID: $userId')),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:18:07