从 Cloud Firestore 集合中获取 Map<String, Map<String, bool>>

时间:2021-02-28 21:15:50

标签: firebase flutter google-cloud-firestore nested

如何从 this Cloud Firestore 集合中获取 Map>? (类型: Map>)

只有布尔值会在 types 中改变,嵌套地图的名称将保持不变!

目前我是这样设置的:

return StreamProvider<List<Info>>.value(
    value: InfoRepo(uid: Constants.userId).info,
    child: StreamBuilder<DocumentSnapshot>(
        stream: Firestore.instance.collection('info').document(Constants.userId).snapshots(), //InfoRepo().infoStream(Constants.userId),
        builder: (context, snapshot) {

            if (snapshot.data == null) {
              return Scaffold(body: LoadingIndicator());
            } else {
              Constants.userAllergens = List<String>.from(snapshot.data.data['allergens']);
              Constants.userPreferences = List<String>.from(snapshot.data.data['preferences']);

              Map<String, dynamic>.from(snapshot.data.data['types']).forEach((key, value) {
              Constants.userTypes.putIfAbsent(key, () => Map<String, bool>.from(value));});   //saves the nested map as a constant

从 Cloud Firestore 获取数据流

Stream<Info> infoStream(String uid) {

 return infoCollection.document(uid).snapshots().map((dataDoc) => Info(
    name: dataDoc.data['name'],
    allergens: List<String>.from(dataDoc.data['allergens']),
    preferences: List<String>.from(dataDoc.data['preferences']),
    types: Map<String, dynamic>.from(dataDoc.data['types'])));
}

我想要这样的东西:

return StreamProvider<List<Info>>.value(
  value: InfoRepo(uid: Constants.userId).info,
  child: StreamBuilder<Info>(
    stream: InfoRepo().infoStream(Constants.userId),
    builder: (context,  snapshot){

      if (snapshot.connectionState == ConnectionState.active) {
        if (snapshot.data == null) {
          return Scaffold(
              body: LoadingIndicator()
          );
        } else {
          Constants.userAllergens = snapshot.data.allergens;
          Constants.userPreferences = snapshot.data.preferences;
          Constants.userTypes = snapshot.data.types;

下面的代码不起作用,只是想展示我一开始是如何尝试的

Stream<Info> infoStream(String uid) {

return infoCollection.document(uid).snapshots().map((dataDoc) =>
    Info(name: dataDoc.data['name'],
        allergens: List<String>.from(dataDoc.data['allergens']),
        preferences: List<String>.from(dataDoc.data['preferences']),
        types: Map<String, Map<String, bool>>.from(dataDoc.data['types'])));

}

我希望能够在别处使用 infoStream 函数,而不是每次调用它时都执行额外的意大利面条式代码。但是函数 infoStream 在需要获取类型的时候似乎无法获取数据——整个过程就会失败。这是因为它是嵌套的,我必须分别通过每个子图吗?

如果有人可以给我一个关于如何正确编写 infoStream 函数的解决方案,那就太好了!!!

谢谢:))

0 个答案:

没有答案