【问题标题】:type 'List<String>' is not a subtype of type 'String' in type cast类型“List<String>”不是类型转换中“String”类型的子类型
【发布时间】:2018-06-29 21:16:47
【问题描述】:

我有这个:

List&lt;String&gt; _filters = &lt;String&gt;[8, 11];

我将这个_filters 传递到这个端点:

this.api.setInterests(token, _filters)
  .then((res) {
    print(res);
  });

看起来像这样:

  Future setInterests(String token, List<String> interests) {
    return _netUtil.post(BASE_URL + "/setinterests", body: {
      "token": token,
      "interests": interests
    }).then((dynamic res) {
      return res;
    });
  }

传递_filters 总是抛出错误:

type 'List&lt;String&gt;' is not a subtype of type 'String' in type cast

我不知道飞镖还想从我这里得到什么。

【问题讨论】:

  • 检查token是否也是字符串类型。还尝试使用 var 而不是 List 定义 _filters 并删除 。对于 Dart 中的大多数用途,这应该足够了。
  • 已检查。 token 是一个字符串。它来自final token = prefs.getString('token');。更改为 var 并不能解决此问题。问题是,错误消息完全没有意义,所以调试甚至开始都含糊不清
  • 使用 var 会抛出这个type 'List&lt;dynamic&gt;' is not a subtype of type 'String' in type cast
  • 你确定body可以接收List的吗?看起来它正试图将其转换为 String 给我,这显然不起作用。
  • @creativecreatorormaybenot 如果是这样,我该如何解决?

标签: dart flutter


【解决方案1】:

我找到了答案。我刚刚将.toString() 添加到_filters 列表中。

  this.api.setInterests(token, _filters.toString())
  .then((res) {
    print(res);
  });

【讨论】:

  • 很高兴听到您解决了问题。我只是写一个评论作为一个友好的提醒。 :) 首先,List&lt;String&gt; _filters = &lt;String&gt;[8, 11]; 这部分给出了错误。这将在下面给我们一个错误。 ` 错误:不能将元素类型“int”分配给列表类型“String”。 ` 我也会修复数组的问题。
【解决方案2】:
  1. 需要在正文中添加json.encode(data)
  2. 添加这两个标题
    “内容类型”:“应用程序/json”,
    '接受':'应用程序/json',
  3. 创建数据地图

    final Map<String, dynamic> data = new Map<String, dynamic>();
     data['token'] = token;
     data['interests'] = interests;
    
  4. 这样调用api

    http.post(url,<br>
    body: json.encode(data),
    headers: { 'Content-type': 'application/json',
      'Accept': 'application/json'},
    encoding: encoding)
    .then((http.Response response) {
    
         // print(response.toString());
    
    }
    

【讨论】:

    【解决方案3】:

    在您的情况下,主体是 Map 因为“params”键映射到列表([])而不是字符串(“[]”)。

    使用join() 函数分隔List &lt;String&gt;,并将每个元素转换为字符串并连接字符串。像这样

    _filters.join('')
    

    如果你想要comma separated string,那么就这样做

    这使您的列表以逗号分隔的字符串

    _filters.join(',')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2021-11-07
      • 2020-06-19
      • 2021-08-29
      • 2020-11-24
      相关资源
      最近更新 更多