首页 > 解决方案 > Flutter / Firestore - 如何访问 Firebase 上的嵌套元素?

问题描述

我正在开发一个英语词汇学习应用程序。
我创建了一些数据类来创建不同的对象:以下是其中两个:

class CarnetWords {
  int? iD;
  int? wrong;
  int? right;
  double? mastery;
  CarnetWords(
      {@required this.iD,
      @required this.wrong,
      @required this.right,
      @required this.mastery});
}

class VocList {
  String? ref;
  String? titre;
  DateTime? creation;
  DateTime? modification;
  DateTime? firstSession;
  DateTime? latestSession;
  double? mastery;
  List<CarnetWords>? wordId;
  VocList(
      {@required this.ref,
      @required this.titre,
      @required this.creation,
      @required this.modification,
      @required this.firstSession,
      @required this.latestSession,
      @required this.mastery,
      @required this.wordId});
}

我的问题是我需要将这些元素上传到 firebase。它工作正常:我设法将我的对象“转换”为地图等......这是在 firebase 上的样子:

这是它在 FIREBASE 上的样子(见图

现在我需要检索这些元素,我只是不知道如何进入“mots”列表并创建我的对象列表。到目前为止,这是我的代码。我尝试使用 ['id']... 显然不起作用...

final _fireStore3 = FirebaseFirestore.instance
        .collection('familyAccounts')
        .doc(id)
        .collection('users')
        .doc('user2')
        .collection('vocList');
    await _fireStore3.get().then((QuerySnapshot querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        _carnetVoc2.add(
          VocList(
            ref: doc['ref'],
            titre: doc['titre'],
            creation: doc['dateCreation'].toDate(),
            modification: doc['dateModification'].toDate(),
            firstSession: doc['firstSession'].toDate(),
            latestSession: doc['latestSession'].toDate(),
            mastery: doc['mastery'].toDouble(),
            wordId: [
              CarnetWords(
                  iD: doc['mots']['id'],
                  wrong: doc['mots']['wrong'],
                  right: doc['mots']['right'],
                  mastery: doc['mots']['mastery'].toDouble())
            ],
          ),
        );
      });
    });

标签: firebasefluttergoogle-cloud-firestorenested-lists

解决方案


也许是这样工作的,首先你遍历列表的元素,然后将列表添加到对象中,

await _fireStore3.get().then((QuerySnapshot querySnapshot) {
  querySnapshot.docs.forEach((doc) {
    List<CarnetWords> carnetWords = [];
    Map mots = doc['mots'];
    
    mots.forEach((index, value){
      carnetWords.add(CarnetWords(id: value.id, wrong: value.wrong, right: value.wrong, mastery: value.mastery.toDouble()));
    });
    
    _carnetVoc2.add(
      VocList(
        ref: doc['ref'],
        titre: doc['titre'],
        creation: doc['dateCreation'].toDate(),
        modification: doc['dateModification'].toDate(),
        firstSession: doc['firstSession'].toDate(),
        latestSession: doc['latestSession'].toDate(),
        mastery: doc['mastery'].toDouble(),
        wordId: carnetWords,
      ),
    );
  });

}


推荐阅读