giorgio79
giorgio79

Reputation: 4189

FireStore fromSnapshot vs fromMap for reading DocumentSnapshot?

I have been wondering which to use for reading a FireStore snapshot, as I can just use fromSnapshot as snapshot["fieldName"] works just fine.

Now, I found an example in Google codelabs at https://codelabs.developers.google.com/codelabs/flutter-firebase/#10

Is this way the definitive way to go? Eg fromSnapshot, and then use fromMap for snapshot.data? What if I dont use fromMap? What am I losing? And then, I have also seen fromJson instead of fromMap...

class Record {
 final String name;
 final int votes;
 final DocumentReference reference;

 Record.fromMap(Map<String, dynamic> map, {this.reference})
     : assert(map['name'] != null),
       assert(map['votes'] != null),
       name = map['name'],
       votes = map['votes'];

 Record.fromSnapshot(DocumentSnapshot snapshot)
     : this.fromMap(snapshot.data, reference: snapshot.reference);

 @override
 String toString() => "Record<$name:$votes>";
}

Upvotes: 2

Views: 1874

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

There is no singular definitive answer for this. Passing a Map into your data class ensures that you can also create an object from data that doesn't come from Firestore. But on the other hand, passing a DocumentSnapshot ensures that you can make use of any extra metadata in that object if needed (it hardly every is, but still).

I think the approach in the Record class is pretty idiomatic: it allows you to use fromMap in places (for example unit tests) that don't use Firestore, but then pass in the DocumentSnapshot when you're actually getting the data from Firestore.

But as said: none of these approaches is wrong, and picking one is as much personal preference as it is an evolving idiom from the community.

Upvotes: 1

Related Questions