FireStore fromSnapshot vs fromMap for reading DocumentSnapshot?

女生的网名这么多〃 提交于 2021-01-28 02:52:15

问题


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>";
}

回答1:


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.



来源:https://stackoverflow.com/questions/63439439/firestore-fromsnapshot-vs-frommap-for-reading-documentsnapshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!