【问题标题】:Complex JSON parsing in FlutterFlutter 中复杂的 JSON 解析
【发布时间】:2020-04-13 14:12:11
【问题描述】:

我需要在我的应用程序中创建一张卡片,但我的应用程序是一个新闻应用程序,并使用 JSON API 从网站调用我的数据,我试图检索应用程序崩溃的新闻图像并给出一条消息:

图像资源服务捕获的异常 解析图像编解码器时引发以下 ArgumentError:无效参数:在 URI 文件:///medium_large 中未指定主机。图片提供者:NetworkImage("medium_large", scale: 1.0) 图片键:NetworkImage("medium_large", scale: 1.0)

代码有什么问题?我可以更好地简化代码吗?

JSON:

{
    "status": "ok",
    "posts": [
        {
            "title": "Barcelona 0-0 Real Madrid: Bale goal disallowed in tense Clasico",
            "content": "Gareth Bale saw a goal disallowed as Barcelona and Real Madrid played out a 0-0 draw at Camp Nou on Wednesday. LaLiga's top two went into the contest level on points this season and with 72 wins each from previous league meetings, and there was nothing to separate them in a tense clash in Catalonia. The match was rearranged from October after the initial date became a security risk due to the prospect of Catalan independence protests, and there were fans inside and outside the stadium making their voices heard over one of Spain's most divisive issues.",
            "date": "2019-12-21 11:27:25",
            "thumbnail_image": {
                "medium_large": {
                    "url": "https://www.livescore.com/newsapi/04/soccer/imageret/barcelona-real-madrid-gareth-bale-goal-disallowed-tense-clasico-7-1cgsl7i8ipuf61gmt7m8ttd60w.jpg"
                }
            }
        }
    ]
}

新闻类:

class News {
  String status;
  List<Posts> posts;

  News({
    this.status,
    this.posts,
  });

  factory News.fromJson(Map<String, dynamic> json) => new News(
        status: json["status"],
        posts:
            new List<Posts>.from(json["posts"].map((x) => Posts.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "posts": new List<dynamic>.from(posts.map((x) => x.toJson())),
      };
}

class Posts {
  String title;
  String content;
  DateTime date;
  PostImage thumbnailImages;

  Posts({this.title, this.content, this.date, this.thumbnailImages});

  factory Posts.fromJson(Map<String, dynamic> postsJson) => new Posts(
        title: postsJson["title"],
        content: postsJson["content"] == null ? null : postsJson["content"],
        date: DateTime.parse(postsJson["date"]),
        thumbnailImages: PostImage.fromJson(postsJson["thumbnail_images"]),
      );

  Map<String, dynamic> toJson() => {
        "title": title,
        "content": content == null ? null : content,
        "date": date.toIso8601String(),
        "thumbnail_images": thumbnailImages.toJson(),
      };
}

class PostImage {
  String mediumImage;
  String url;

  PostImage({ this.mediumImage, this.url });

  factory PostImage.fromJson(Map<String, dynamic> imgJson) => new PostImage(
      mediumImage: "medium_large",
  );

  Map<String, dynamic> toJson() => {
    "medium_large": mediumImage,
  };
}

列表新闻:

class ListItem extends StatelessWidget {
  final Posts posts;

  ListItem(this.posts);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(
          textDirection: TextDirection.rtl,
      children: <Widget>[
        Container(
          height: 400,
          width: 220,
          child: Image.network(posts.thumbnailImages.mediumImage),
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.all(8),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    posts.title,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.right,
                    maxLines: 2,
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                ]),
          ),
        )
      ],
    ));
  }
}

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    尝试添加 .url

    child: Image.network(posts.thumbnailImages.mediumImage.url),
    

    工作代码: Gist

    【讨论】:

    【解决方案2】:

    您必须更改您的 PostImage 课程。并添加另一个类MediumLarge

    class PostImage {
      MediumLarge mediumLarge;
    
      PostImage({
        this.mediumLarge,
      });
    
      factory PostImage.fromJson(Map<String, dynamic> json) => PostImage(
            mediumLarge: MediumLarge.fromJson(json["medium_large"]),
          );
    
      Map<String, dynamic> toJson() => {
            "medium_large": mediumLarge.toJson(),
          };
    }
    
    class MediumLarge {
      String url;
    
      MediumLarge({
        this.url,
      });
    
      factory MediumLarge.fromJson(Map<String, dynamic> json) => MediumLarge(
            url: json["url"],
          );
    
      Map<String, dynamic> toJson() => {
            "url": url,
          };
    }
    

    然后使用

    Container(
      height: 400,
      width: 220,
      child: Image.network(posts.thumbnailImages.mediumImage.url),
    )
    

    有一个网站可以为 json 生成 dart 类。 QuickType

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 2021-06-20
      • 2020-12-21
      • 2020-10-21
      • 1970-01-01
      • 2021-07-20
      • 2022-01-10
      相关资源
      最近更新 更多