【发布时间】:2019-07-19 00:42:20
【问题描述】:
简短: toList() 在 makeMaker 之前执行,导致 markers 具有 null 对象。
Long:在 Firestore 中,我有 table 和 game 集合,在 table 内部,有一个 game 字段(type=reference)。使用StreamBuilder,我可以访问tables。我遍历tables 并尝试使用get 用真实数据填充他们的game 字段,如下所示;
if (snapshot.hasData) {
tabledocs = snapshot.data.documents;
markers = tabledocs
.map((tabledoc) {
DocumentReference gameref = tabledoc.data['game'];
//game field is a reference type field which points to another collection
gameref.get().then((gdoc) {
tabledoc.data['game'] = gdoc;
Marker marker = makeMarker(tabledoc); //<--------Executes later
return marker;
});
}).toList(); //<--------Executes first
}
因为gameref.get().then() 需要时间,所以底部的toList() 在每个标记生成并添加到markers 之前执行。
如果有 3 个标记从 Firestore 返回,我们的 markers 是一个由 3 个 null markers 组成的数组。我认为makeMarker(..) 很可能还没有执行。
有没有办法让map 方法等待gets 完成,然后用非空值初始化markers 数组?或者你能告诉我另一种方法来完成我想要的。
【问题讨论】:
标签: dart flutter google-cloud-firestore future dart-async