在类型转换中,'List<String>' 类型不是 'String' 类型的子类型。

7

我有这个:

List<String> _filters = <String>[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总是会引发错误:

类型“List<String>”不是类型转换中的“String”的子类型

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


检查令牌是否为字符串类型。另外,尝试使用变量定义_filters而不是List<String>,并删除<String>。这在Dart中应该已经足够了。 - Bostrot
1
已检查。token是一个字符串。它来自于final token = prefs.getString('token');。将其更改为var并不能解决问题。问题在于,错误信息根本没有意义,所以调试甚至无从开始。 - KhoPhi
使用 var 会抛出以下错误 type 'List<dynamic>' is not a subtype of type 'String' in type cast - KhoPhi
你确定 body 可以接受 List 吗?在我看来,它似乎试图将其转换为 String,显然这是行不通的。 - creativecreatorormaybenot
@creativecreatorormaybenot 如果是这样,我该如何修复它? - KhoPhi
2个回答

5
我找到了答案。我只是向 _filters 列表添加了 .toString()
  this.api.setInterests(token, _filters.toString())
  .then((res) {
    print(res);
  });

好听到您已解决了问题,我只是想作为友善的提醒写下此评论 :) 首先, List<String> _filters = <String>[8, 11]; 这部分代码出现了错误。 这会导致以下错误: error: The element type 'int' can't be assigned to the list type 'String'. 我也会修复数组问题。 - salihgueler

3
  1. You need to add json.encode(data) in body
  2. Add these two header
    'Content-type': 'application/json',
    'Accept': 'application/json',
  3. Create map of your data

    final Map<String, dynamic> data = new Map<String, dynamic>();
     data['token'] = token;
     data['interests'] = interests;
    
  4. Call api like this

    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());
    
    }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接