Issue
In the example below, I'm trying to add a parsedJson['newElement']
field check to my firestore data. The problem is, if this field doesn't exist in the firestore collection map being returned, it throws a null and the entire function fromJson
fails because of this null... Right now my code allows for a null value from the field being returned and this works fine. But how do I fail safely and assign a blank value on fields that may not exist yet? I'm assuming that I'm missing something easy here.
factory ItemModel.fromJson(Map<String, dynamic> parsedJson) {
return ItemModel(
authorID: parsedJson['authorID'] ?? '',
authorName: parsedJson['authorName'] ?? '',
newElement: parsedJson['newElement'] ?? '',
);
Solution
You can make the fields nullable like so:
class ItemModel{
String? authorID;
String? authorName;
String? newElement;
ItemModel({this.authorID, this.authorName, this.newElement});
factory ItemModel.fromJson(Map<String, dynamic> parsedJson){
return ItemModel(
authorID: parsedJson["authorID"],
authorName: parsedJson["authorName"],
newElement: parseJson["newElement"],
);
}
}
Answered By - Josteve
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.