【问题标题】:flutter get data from api type 'String' is not a subtype of type 'Map<String, dynamic>'颤振从 api 类型“String”获取数据不是“Map<String, dynamic>”类型的子类型
【发布时间】:2021-05-09 13:40:29
【问题描述】:

这是我的测试代码 尝试搜索但不工作.. 这将是我错过的东西.. 请帮我解决这个问题。

test('http test', () async {
        var uri = Uri.parse(
            'https:....posts.json');
        var response = await http.get(uri);
        expect(response.statusCode, 200);

        NewsInfo newsInfo = NewsInfo.fromJson(jsonDecode(json.encode(response.body)));

        expect(newsInfo.id, "dc523f0ed25c");
      }); 

这个 id json 到 dart

class NewsInfo {
  String id;
  int imageId;
  int imageThumbId;
  Metadata metadata;
  List<Paragraphs> paragraphs;
  Publication publication;
  String subtitle;
  String title;
  String url;

  NewsInfo(
      {this.id,
        this.imageId,
        this.imageThumbId,
        this.metadata,
        this.paragraphs,
        this.publication,
        this.subtitle,
        this.title,
        this.url});
  NewsInfo.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    imageId = json['imageId'];
    imageThumbId = json['imageThumbId'];
    metadata = json['metadata'] != null
        ? new Metadata.fromJson(json['metadata'])
        : null;
    if (json['paragraphs'] != null) {
      paragraphs = new List<Paragraphs>();
      json['paragraphs'].forEach((v) {
        paragraphs.add(new Paragraphs.fromJson(v));
      });
    }
    publication = json['publication'] != null
        ? new Publication.fromJson(json['publication'])
        : null;
    subtitle = json['subtitle'];
    title = json['title'];
    url = json['url'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
..

json下面是这样的

[
  {
    "id": "dc523f0ed25c",
    "imageId": 2131165292,
    "imageThumbId": 2131165293,
    "metadata": {
      "author": {
        "name": "Pietro Maggi",
        "url": "https://medium.com/@pmaggi"
      },
      "date": "August 02",
      "readTimeMinutes": 1
    },
    "paragraphs": [
      {
        "markups": [],
        "text": "Working to make our Android application more modular, I ended up with a sample that included a set of on-demand features grouped inside a folder:",
        "type": "Text"
      },
      

当我运行测试时它显示 测试/widget_test.dart 23:47 主要。 “String”类型不是“Map”类型的子类型 尝试搜索但不工作.. 这将是我错过的东西.. 请帮我解决这个问题。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您的 json 响应看起来像一个列表。试试

    List<NewsInfo> news = json.decode(response.body).map((el) => NewsInfo.fromJson(el)).toList();
    

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 2021-11-20
      • 2021-06-28
      • 2020-01-18
      • 2023-04-02
      • 2021-10-06
      • 1970-01-01
      • 2018-12-14
      • 2021-10-25
      相关资源
      最近更新 更多