【问题标题】:problem with casting a custon list in flutter在颤振中投射自定义列表的问题
【发布时间】:2021-06-13 15:53:22
【问题描述】:

我想删除已弃用的消息,但无论如何我更改代码项目出错了。

if (json['images'] != null) {
images = new List<Images>();
List<Images> images = new List<Images>();

json['images'].forEach((v) {
images.add(new Images.fromJson(v));
});
}
class Images {
String src;

Images({this.src});
    
Images.fromJson(Map<String, dynamic> json) {
src = json['src'].toString();
}
}

我试过了:

List<Images> images = new List<Images>();
images = new List<Images>();
List<Images> images = []..length = 500;

【问题讨论】:

  • 错误信息是什么?您的代码在第 2 行和第 3 行是错误的。您资产 json['images'] 不为空,但您使用的 json['src'] 也可以为空
  • 请提供您的json对象和错误信息
  • 你的 'images' json 数据结构是什么样的?
  • 天啊。第 3 行实际上不在主要代码中。
  • 我没有错误,但是当运行该代码时(当第 2 行注释和第 3 行 id 处于活动状态时),我有这个:

标签: list flutter deprecated


【解决方案1】:

如果我没记错的话,您是在尝试解析一组图像的 JSON,对吧?如果是这种情况,则说明您没有正确执行此操作。这是解决方案:

class Image {
  String src;

  const Image({ this.src });

  factory Image.fromJson(Map<String, dynamic> json) {
    return Image(src: json['src']);
  }
}

// First, we cast the json as a dynamic list
final list = json['images'] as List;

// Then iterate over it using map to create a new list
final images = list.map((json) => Image.fromJson(json)).toList();

// There you have it
print(images.runtimeType); // output: List<Image>

// You can also do a loop with it
images.forEach((image) => print(image.src));

为了安全起见,您可能希望在执行这些操作之前先进行一次空值检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多