FireStore fromSnapshot vs fromMap用于读取DocumentSnapshot? [英] FireStore fromSnapshot vs fromMap for reading DocumentSnapshot?

查看:60
本文介绍了FireStore fromSnapshot vs fromMap用于读取DocumentSnapshot?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想使用哪个来读取FireStore快照,因为我可以只使用fromSnapshot,因为 snapshot ["fieldName"] 可以正常工作.

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

现在,我在Google代码实验室的 https://上找到了一个示例codelabs.developers.google.com/codelabs/flutter-firebase/#10

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

这是确定的方法吗?例如fromSnapshot,然后将fromMap用于snapshot.data?如果我不使用fromMap怎么办?我输了什么?然后,我也看到了fromJson而不是fromMap ...

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

推荐答案

对此没有唯一的明确答案.将 Map 传递到数据类可确保您还可以使用非Firestore数据创建对象.但是另一方面,传递 DocumentSnapshot 可以确保您在需要时可以使用该对象中的任何其他元数据(几乎每一个都可以,但是仍然可以).

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).

我认为 Record 类中的方法非常惯用:它允许您在不使用Firestore的地方(例如单元测试)使用 fromMap ,但是当您实际上是从Firestore获取数据时,然后传递 DocumentSnapshot .

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.

这篇关于FireStore fromSnapshot vs fromMap用于读取DocumentSnapshot?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆