【问题标题】:Flutter for web, how to convert List<dynamic> to List<Item>?Flutter for web,如何将 List<dynamic> 转换为 List<Item>?
【发布时间】:2020-08-03 03:27:33
【问题描述】:

Flutter 网络

我从json.decode(res.body) 得到List&lt;dynamic&gt;

并且无法转换为我预期的类型List&lt;Item&gt;

在 chrome 开发工具中,它会抛出

Uncaught (in promise) Error: Type 'List<dynamic>' should be 'List<Item>' to implement expected type 'FutureOr<List<Item>>'.

这是我的代码

import 'package:http/http.dart' as http;

class ApiService {
  static Future get({String url, Object params}) async {
    final res = await http.get(_root + url);
    return json.decode(res.body);
  }

  /// get 30 items of specific content type
  static Future<List<Item>> getContentList({String type, num page = 1}) async {
    final List<dynamic> ret = await ApiService.get(
      url: _typeMap[type],
    );
    // If I try `ret.cast<Item>()` it will also throw something like `... type _JsonMap ...`
    return ret;
  }
}

response body 是黑客新闻列表,

[{comments_count: 466,
domain: "github.com",
id: 22925087,
points: 1162,
time: 1587398440,
time_ago: "8 hours ago",
title: "Shirt Without Stripes",
type: "link",
url: "https://github.com/elsamuko/Shirt-without-Stripes",
user: "elsamuko",
}]

我该如何解决这个问题?

【问题讨论】:

  • 请分享您的 json 和您尝试解码 json 的代码。

标签: flutter flutter-web


【解决方案1】:

看起来响应正文应该是地图列表。要将其转换为List&lt;Item&gt;,您的Item 类将需要fromJson 构造函数。

class Item {
  ...
  Item.fromJson(...)
      : ...
}

查看此链接以了解如何实现此功能:https://medium.com/flutter-community/how-to-parse-json-in-flutter-for-beginners-8074a68d7a79

那么您所要做的就是将此函数映射到列表中的所有对象。

  static Future<List<Item>> getContentList({String type, num page = 1}) async {
    final List<dynamic> ret = await ApiService.get(
      url: _typeMap[type],
    );
    return ret.map((obj) => Item.fromJson(obj)).toList();
  }

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2020-12-18
    • 2021-05-27
    • 1970-01-01
    • 2021-05-20
    • 2020-09-04
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多