firebase - 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 上的样子:
现在我需要检索这些元素,我只是不知道如何进入“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())
],
),
);
});
});
解决方案
也许是这样工作的,首先你遍历列表的元素,然后将列表添加到对象中,
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,
),
);
});
}
推荐阅读
- python - 给定另一个列子集中的信息,在 Pandas DataFrame 的列子集中重新排序行中的项目
- awk - 使用 awk 对大文本文件中的行进行分组和汇总
- docker - Traefik 基于路径的路由
- jquery - Ajax 调用返回“未定义” - Companies House API
- c# - 将文件 20181207_ProdAndPressuresExport.csv 重命名为 ProdAndPressuresExport.csv
- javascript - 避免使用 node.js & shelljs 同时执行 shell 命令
- javascript - 移动数组项时,嵌入的 Youtube 视频在组件内重新加载,使用 v-for 渲染
- c - 如何在 fork 上的子进程期间在字符串上打印 \n
- github - 将随机 GitHub 存储库编译成 AST 的风险?
- reactjs - 在 Gatsby 中将页面状态传递给布局