Flutter:解码 List<dynamic> 到 List<String> 静默失败

Flutter: Decoding List<dynamic> to List<String> silently failing

当从 Json 列表对象转换为列表字符串时,该过程不会失败,而是静静地失败,没有任何警告或错误来确定出了什么问题。

重现步骤

取下面的工厂和型号:

class Topic {
  int? id;
  String name;
  String displayName;
  int? parentId;
  List<String>? contentThemes;
  List<String>? channels;

  Topic({this.id, required this.name, required this.displayName, this.parentId, this.contentThemes, this.channels});

  factory Topic.fromJson(Map<String, dynamic> json) {
    var topic = Topic(
      id: json['id'] as int?,
      name: json['name'] as String,
      displayName: json['displayName'] as String,
      parentId: json['parentId'] as int?,
      contentThemes: json['contentThemes'] as List<String>?,
      channels: json['channels'] as List<String>?,
    );

    return topic;
  }
}

预期结果:

期望 flutter 能够识别出 json['contentThemes'] 不是复杂对象,并将其从 List dynamic 转换为 List String

或者如果不能,它应该向开发者抛出一个错误来强调投射失败。

实际结果: 当尝试将 List 转换为 List (contentThemes, channels) 时,它会停止执行并默默地无法完成任务,因此永远不会返回数据。

目前的解决方法是将其视为一个复杂对象并执行如下操作:

class Topic {
  int? id;
  String name;
  String displayName;
  int? parentId;
  List<String>? contentThemes;
  List<String>? channels;

  Topic({this.id, required this.name, required this.displayName, this.parentId, this.contentThemes, this.channels});

  factory Topic.fromJson(Map<String, dynamic> json) {
    var topic = Topic(
      id: json['id'] as int?,
      name: json['name'] as String,
      displayName: json['displayName'] as String,
      parentId: json['parentId'] as int?,
      contentThemes: (json['channels'] as List?)?.map((item) => item as String)?.toList(),
      channels: (json['contentThemes'] as List?)?.map((item) => item as String)?.toList()
    );

    return topic;
  }
}

希望这对其他人有所帮助,因为由于 flutter 当前处理此问题的方式,这是一个难以调试的问题。

试试这个:

channels: List<String>.from(json['contentThemes'].map((x) => x))