Flutter for web,如何将 List<dynamic> 转换为 List<Item>?

Flutter for web, how to convert List<dynamic> to List<Item>?

Flutter Web

我从 json.decode(res.body)

得到 List<dynamic>

并且无法转换为我期望的类型 List<Item>

在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;
  }
}

响应体为黑客新闻条目列表,

[{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",
}]

我该如何解决?

看起来响应正文应该是地图列表。要将其转换为 List<Item>,您的 Item class 将需要一个 fromJson 构造函数。

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

查看这个 link 以了解如何实现它: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();
  }