Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter Cloudfirestore: how to check whether field exists

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do it like so.

newFeature: (snapshot.data() as Map)['newFeature'] ?? ''
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading