Flutter应用无法通过FCM发送推送通知:Postman正常代码无效
解决FCM推送通知Flutter代码不生效问题
针对你Postman发送正常、Flutter代码无法推送的情况,从代码里排查出几个核心问题,对应修复方案如下:
1. 检查Authorization头格式
FCM的Authorization头必须以key=开头,很多开发者会忽略这个前缀。确认你的serverToken变量是否包含这个前缀,如果没有,修改headerMap:
Map<String, String> headerMap = { 'Content-Type': 'application/json', 'Authorization': 'key=$serverToken', // 确保key=前缀存在 };
2. 修复notification字段的语法错误
代码中notificationMap的body值有未闭合的双引号:'DropOff Address, "Destination',这会导致JSON编码后格式非法,FCM服务器会拒绝请求。修正为合法字符串:
Map notificationMap = { 'body': 'DropOff Address, Destination', // 移除多余的未闭合引号 'title': 'New Ride Request' };
如果需要包含引号,要转义:'DropOff Address, \"Destination\"'
3. 打印FCM响应信息排查错误
当前代码没有捕获和打印HTTP响应的状态码与内容,无法知道FCM服务器返回的具体错误(比如权限错误、格式错误)。修改代码添加响应日志:
try { print("try for messaging"); var response = await http.post( Uri.parse('https://fcm.googleapis.com/fcm/send'), headers: headerMap, body: jsonEncode(sendNotificationMap), ); print("FCM响应状态码: ${response.statusCode}"); print("FCM响应内容: ${response.body}"); } catch (e) { print("error firebase messaging = " + e.toString()); }
根据响应内容可以精准定位问题,比如401 Unauthorized说明权限错误(key不对或前缀缺失),400 Bad Request说明JSON格式错误。
4. 确认token的有效性
虽然你打印了token,但要确保该token是当前设备的有效FCM token,没有过期或被注销。可以在Postman中使用相同的token测试,对比代码里的token是否一致。
修改后的完整代码示例
static sendNotificationToDriver( String token, context, String ride_request_id) async { print("Token = " + token); print("RIDE REQUEST = " + ride_request_id); Map<String, String> headerMap = { 'Content-Type': 'application/json', 'Authorization': 'key=$serverToken', // 补全key=前缀 }; Map notificationMap = { 'body': 'DropOff Address, Destination', // 修复字符串语法 'title': 'New Ride Request' }; Map dataMap = { 'click_action': 'FLUTTER_NOTIFICATION_CLICK', 'id': '1', 'status': 'done', 'ride_request_id': ride_request_id, }; Map sendNotificationMap = { "notification": notificationMap, "data": dataMap, "priority": "high", "to": token, }; try { print("try for messaging"); var response = await http.post( Uri.parse('https://fcm.googleapis.com/fcm/send'), headers: headerMap, body: jsonEncode(sendNotificationMap), ); // 新增响应日志 print("FCM Status Code: ${response.statusCode}"); print("FCM Response Body: ${response.body}"); } catch (e) { print("error firebase messaging = " + e.toString()); } }
内容的提问来源于stack exchange,提问作者Uzair Haider
相关产品推荐
相关产品推荐

