Flutter中Firebase getInitialMessage提取payload遇类型转换异常
解决Firebase Messaging getInitialMessage获取Awesome Notifications payload的类型异常
问题重现
在Flutter中使用Firebase Messaging的getInitialMessage()方法获取RemoteMessage.data时,因Awesome Notifications的特定消息结构,提取payload字段时报错:
{content: {"channelKey":"big_picture","payload":{"screen":"retreat-video","links":"https://www.youtube.com/watch?v=neFEJxwyYKo"},"thumbNailUrl1":"https://www.dw.com/image/49519617_303.jpg","largeIcon":"https://cdn.pixabay.com/photo/2023/03/19/07/34/car-7862030_960_720.jpg","notificationLayout":"BigPicture","autoDismissible":true,"id":"100","title":"Huston! The eagle has landed!","body":"A small step for a man, but a giant leap to flutters community!","bigPicture":"https://cdn.pixabay.com/photo/2023/03/19/07/34/car-7862030_960_720.jpg"}} I/flutter (23855): ----------------------------- E/flutter (23855): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
错误代码片段:
FirebaseMessaging.instance.getInitialMessage().then((message) { if (message.data != null) { print("${message.data}"); print("-----------------------------"); print("data is here: ${message.data["content"]['payload']}");
原因分析
从日志输出可以看出,message.data["content"]的值是JSON格式的字符串,而非直接可访问的Map对象。直接用['payload']访问该字符串,相当于把字符串当成列表使用int类型索引取值,因此触发类型转换异常。
解决方法
先将content对应的JSON字符串解析为Map对象,再提取其中的payload字段。需要使用dart:convert库的jsonDecode方法。
修正后的代码
import 'dart:convert'; // ... FirebaseMessaging.instance.getInitialMessage().then((message) { if (message?.data != null) { print("${message.data}"); print("-----------------------------"); try { // 解析content字符串为Map final contentMap = jsonDecode(message.data["content"]) as Map<String, dynamic>; // 提取payload final payload = contentMap['payload']; print("data is here: ${payload}"); // 可进一步提取payload内的字段 if (payload != null) { final screen = payload['screen']; final links = payload['links']; print("跳转页面: $screen, 链接: $links"); } } catch (e) { print("解析content失败: $e"); } } });
注意事项
添加try-catch块可以处理content不是有效JSON字符串的边界情况,避免程序崩溃。
内容的提问来源于stack exchange,提问作者Man Steel
相关产品推荐
相关产品推荐

