将 map 转换为对象 给我 null 属性对象

converting map to object give me null properties object

提问人:danial s 提问时间:11/17/2023 最后编辑:danial s 更新时间:11/20/2023 访问量:28

问:

这是 Retrofit 为我构建的代码,我对其进行了一些更改。

_result 是一个 Response<Map<String,动态>>它使用 dio.fetch() 获取


    List<ArticleModel> value = _result.data!['articles']
        .map<ArticleModel>(
            (dynamic i) => ArticleModel.fromJson(i as Map<String, dynamic>))
        .toList();

下面是 fromJson ArticleModel 构造函数

class ArticleModel extends ArticleEntity {
  const ArticleModel({
    int? id,
    String? author,
    String? title,
    String? description,
    String? url,
    String? urlToImage,
    String? publishedAt,
    String? content,
  });


  factory ArticleModel.fromJson(Map<String, dynamic> map) {
    return ArticleModel(
      author: map['author'] ?? '',
      title: map['title'] ?? '',
      description: map['description'] ?? '',
      url: map['url'] ?? '',
      urlToImage: map['urlToImage'] ?? '',
      publishedAt: map['publishedAt'] ?? '',
      content: map['content'] ?? '',
    );
  }
}

我向它添加了一些日志,但第二个日志给了我一个具有 null 属性的对象

    log(_result.data!['articles'][0]['title'], name: 'title'); -> gives me correct title string


    List<ArticleModel> value = _result.data!['articles']
        .map<ArticleModel>(
            (dynamic i) => ArticleModel.fromJson(i as Map<String, dynamic>))
        .toList();

    log(value[0].toString(), name: 'articleModel'); -> gives me ArticleModel(null, null, ...)
json 颤振

评论


答:

0赞 danial s 11/20/2023 #1

我只需要这样做

class ArticleModel extends ArticleEntity {
  const ArticleModel({
    id,
    author,
    title,
    description,
    url,
    urlToImage,
    publishedAt,
    content,
  }) : super(
          id: id,
          author: author,
          title: title,
          description: description,
          url: url,
          urlToImage: urlToImage,
          publishedAt: publishedAt,
          content: content,
        );

感谢 Dragonfly02