When casting from a Json list object to a list String, instead of failing to cast, the process silently fails without any warnings or errors to identify what is going wrong.
Steps to Reproduce
Take the below factory and model:
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;
}
}
Expected results:
The expectation is that flutter is able to identify that json['contentThemes'] is not a complex object and cast it from List dynamic to List String
OR if it is unable to, it should throw an error to the developer to highlight the failure to cast.
Actual results: When trying to cast List to List (contentThemes, channels) it stops execution and silently fails to complete the task so the data is never returned.
The work around currently is to treat this as a complex object and do something like this:
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;
}
}
Hope this helps anyone else as this was a tricky issue to debug due to the way flutter currently handles this.
CodePudding user response:
Try this:
channels: List<String>.from(json['contentThemes'].map((x) => x))