有没有一个方法,使用Firestorage,将一个集合转换为一个地图列表,没有Streambuilder / widget?

问题描述 投票:2回答:1

有没有一个方法,使用Firestorage,将一个集合转换为一个地图列表,没有Streambuilder / widget?

示例:我有一个包含文档的集合“exampleData”。我需要使用集合的数据从中创建“地图列表”。数据示例:

List<Map> exampleData = [map1,map2,map3]

该列表中的元素包含如下数据:

map1 = {
"active":"true"
"age" = "2"
"editing" = "false"
"photo_url" = "https://test.com"
"score: 0"
}
dart google-cloud-firestore flutter
1个回答
6
投票

假设你有一个名为listOfMaps的变量,它的类型为List<Map>

List<Map> listOfMaps;

您可以为该对象提供集合的实时更新,如下所示:

final Stream<List<Map>> mappedStream = collectionReference.snapshots().map((QuerySnapshot snapshot) {
  // returning a Map that contains all values marked in your screenshot
  return snapshot.documents.map((DocumentSnapshot document) => document.data);
});

// assigning the data to the listOfMaps by listening to the Stream
mappedStream.listen((List<Map> data) => listOfMaps = data);

我们可以使用snapshots() Stream<List<QuerySnapshot>>来获取包含所有文档作为对象的StreamDocumentSnapshot)。为此,我们可以使用map函数将List<QuerySnapshot>转换为List<Map

data property中每个DocumentSnapshotList<DocumentSnapshot>与数据库中的每个字段都有一个List<Map>

// alternatively the Stream can be used e.g. in a StreamBuilder
StreamBuilder(
  stream: mappedStream,
  builder: ...
);

总结一下:

  • 在转换之前,我们可以从List<DocumentSnapshot> snapshots()获得Stream
  • 之后,我们通过使用List<Map>data属性将其转换为DocumentSnapshots
  • mappedStream可以被收听,例如将数据分配给我们的应用程序中的对象或用于像StreamBuilder这样的东西
© www.soinside.com 2019 - 2024. All rights reserved.