My Flutter app uses Firbase Cloudfirestore as its backend. Later I'll want to add new features to my app which would require new fields in a Firestore document. How can I check whether the field exists in the document and return a default value if it doesn't?
Stream<List<Car>> streamCars() {
return _carsCollection.snapshots().map((snapshot) => snapshot.docs.map((document) => Car.fromDocumentSnapshot(document)).toList());
}
static Car fromDocumentSnapshot(DocumentSnapshot snapshot) {
return Car(
id: snapshot.id,
date: snapshot['date'] ?? Timestamp.now(),
seats: snapshot['seats'] ?? 0,
newFeature: snapshot['newFeature'] ?? '', // This field does not exist yet and throws error
);
}
This throws the error:
Bad state: field does not exist within the DocumentSnapshotPlatform
CodePudding user response:
You can do it like so.
newFeature: (snapshot.data() as Map)['newFeature'] ?? ''
CodePudding user response:
static Car fromDocumentSnapshot(DocumentSnapshot snapshot) {
return Car(
id: snapshot.id,
date: snapshot['date'] ?? Timestamp.now(),
seats: snapshot['seats'] ?? 0,
newFeature: snapshot['newFeature']==null ?'tjhjhjh': '', // check it if is null will solve the error
);
}