【问题标题】:_CastError (type 'Client' is not a subtype of type 'List<dynamic>' in type cast)_CastError(类型 'Client' 不是类型转换中类型 'List<dynamic>' 的子类型)
【发布时间】:2020-01-24 23:50:26
【问题描述】:

我的 API 返回以下响应:

[{id: 1, nome: foo}, {id: 2, nome: bar}]

我创建了一个模型Client 来代表每个人:

class Client {
  final int id;
  final String name;

  Client({
    this.id,
    this.name,
  });

  factory Client.fromJson(Map<String, dynamic> json) {
    return Client(
      id: json['id'],
      name: json['nome'],
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'nome': name,
      };
}

那么,在我的仓库中,上面获取数据的方法如下:

Future<List<Client>> getClients() async {
  try {
    final _response = await _dio.get(
      '/clientes',
      options: Options(
        headers: {'Authorization': 'Bearer $TOKEN'},
      ),
    );

    return Client.fromJson(_response.data[0]) as List; // Error pointed to this line
  } on DioError catch (_e) {
    throw _e;
  }
}

存储在这里

@observable
List<Client> clients;

我不知道该怎么做。我做错了什么?

【问题讨论】:

    标签: json flutter dart model


    【解决方案1】:

    dio 将对响应进行解码,您将得到一个List&lt;dynamic&gt;。使用List.map 将其转换为客户端列表,方法是传递一个将Map&lt;String, dynamic&gt; 转换为Client 的函数。 (您已经有一个 - 命名构造函数。)

    例如:

      var dioResponse = json.decode('[{"id": 1, "nome": "foo"}, {"id": 2, "nome": "bar"}]');
    
      List<dynamic> decoded = dioResponse;
      var clients = decoded.map<Client>((e) => Client.fromJson(e)).toList();
    

    【讨论】:

    • 它抛出一个指向json.decode的错误说_type 'String' is not a subtype of type 'FutureOr&lt;List&lt;Client&gt;&gt;'
    • 好的,看来已经部分解决了。现在的错误是type 'List&lt;void&gt;' is not a subtype of type 'List&lt;DropdownMenuItem&lt;Client&gt;&gt;
    • 你没有显示任何可能创建的代码
    • 是的,我知道。自从第一个问题出现后就没有放任何东西。
    • 既然该部分已解决,我会将您的部分标记为正确的部分。现在这是一个不同的问题。
    【解决方案2】:

    您正在尝试将Client 转换为List&lt;dynamic&gt;,这不是有效的转换,因为Client 没有实现List。如果要返回包含单个 ClientList,则需要将错误行更改为:

    return [Client.fromJson(_response.data[0])];
    

    【讨论】:

    • 我想要的不仅仅是一个,而是整个响应。我做了一个for 循环,将每个Client 添加到新变量类型Client 中,然后返回List&lt;Client&gt;。现在,我面对type 'MappedListIterable&lt;Client, void&gt;' is not a subtype of type 'List&lt;DropdownMenuItem&lt;Client&gt;&gt;'
    • .toList() 会将可迭代对象转换为列表。看起来您还需要一个 map 来将客户端变成下拉菜单项。
    • 啊,那不是您的代码在那里所做的。它只是试图将单个Client 转换为List
    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 2021-08-29
    • 2022-08-16
    • 2021-10-20
    • 2019-12-31
    • 2021-06-23
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多