Home > Software engineering >  Flutter: prevent null crash on element that doesn't exist yet in firestore schema
Flutter: prevent null crash on element that doesn't exist yet in firestore schema

Time:03-07

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'] ?? '',
);

CodePudding user response:

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"],
   );
 }
}
  • Related