【问题标题】:How to send an array in dart post request如何在飞镖发布请求中发送数组
【发布时间】:2019-11-22 19:43:16
【问题描述】:

我尝试使用registration_ids 向设备组发送消息。

这是我的代码:

List<String> tokens=["token1","token2"];
final  url='https://fcm.googleapis.com/fcm/send';
 http.post(url,headers:{
  "Accept": "application/json",
  "Authorization":"key=mykey"
  ,"project_id":"proID"
},
body: 
  {
 "registration_ids" :tokens ,
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "Body of Your Notification",
     "title": "Title of Your Notification"
 }
}

当应用程序运行时显示此错误:

发生了异常。 _CastError(类型'List'不是类型转换中类型'String'的子类型)

如何解决?

【问题讨论】:

    标签: android flutter dart firebase-cloud-messaging


    【解决方案1】:

    由于注册需要JSON 字符串,但您正在将列表对象传递给它,因此您遇到了问题。您可以通过将List&lt;String&gt; 转换为String 来解决这个问题。

    通过使用toString() 方法转换令牌列表,您将得到一个类似"['token1','token2']" 的字符串

    修改后的代码如下:

    List<String> tokens=["token1","token2"];
    final  url='https://fcm.googleapis.com/fcm/send';
     http.post(url,headers:{
      "Accept": "application/json",
      "Authorization":"key=mykey"
      ,"project_id":"proID"
    },
    body: 
      {
     "registration_ids" : tokens.toString() ,
     "collapse_key" : "type_a",
     "notification" : {
         "body" : "Body of Your Notification",
         "title": "Title of Your Notification"
     }
    }
    

    【讨论】:

    • 不工作,它只是作为字符串而不是列表传递。
    【解决方案2】:

    问题解决了;我只是对正文进行了编码:

    List<String> tokens=["token1","token2"];
    final  url='https://fcm.googleapis.com/fcm/send';
     http.post(url,headers:{
      "Accept": "application/json",
      "Authorization":"key=mykey"
      ,"project_id":"proID"
    },
    body:json.encode( 
      {
     "registration_ids" :tokens ,
     "collapse_key" : "type_a",
     "notification" : {
         "body" : "Body of Your Notification",
         "title": "Title of Your Notification"
     }
    )
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 2014-03-09
      • 1970-01-01
      • 2022-01-22
      • 2020-05-03
      • 2019-10-28
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多