如何使用 Flutter 获取 Firestore 中每个集合的子集合 [英] How to get sub-collections of every collection in Firestore using Flutter
问题描述
我正在构建一个任务管理应用,其中每个用户都有多个项目(集合),每个项目内部都有任务(集合),每个任务内部都有子任务.
I'm building a task management app where every user has multiple projects (collections), inside every project there are tasks (collections), and inside every task there are sub-tasks.
我能够使用此代码检索所有项目:
I was able to retrieve all the projects using this code:
User user = Provider.of<User>(context);
CollectionReference projects = Firestore.instance.collection('users').document(user.uid).collection("projects");
但我的问题是如何从每个项目中获取所有任务和子任务(如果存在)并将它们列在 StreamBuilder 中?
But my question is how can I get all the tasks and sub-tasks (if they exist) from every project and list them in a StreamBuilder?
这是我当前的代码:
Flexible(
child: StreamBuilder<QuerySnapshot>(
stream: projects.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return new ListView(
children:
snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document.data['project_name']),
subtitle: new Text(document.data['project_description']),
);
}).toList(),
);
},
),
),
如果项目有任务我想在项目描述下面显示它们,如果任务有子任务我想在它的父任务下面显示它们.
If the project has tasks I want to display them below the project description, and if the task has sub-tasks I want to show them below its parent task.
推荐答案
听起来您本质上是在问如何列出嵌套的子集合,这对于 Web 和移动客户端来说是不可能的.另见:
It sounds like you're essentially asking how to list nested subcollections, which is not possible for web and mobile clients. See also:
此外,所有 Firestore 查询都很浅,这意味着它们一次只考虑一个集合中的文档.没有深度或递归查询.
Also, all Firestore queries are shallow, meaning they only consider documents in one collection at a time. There are no deep or recursive queries.
考虑在文档中维护项目列表,您可以直接get()
.您可以使用该列表直接查询每个子集合.
Consider instead maintaining the list of projects in a document that you can get()
directly. You can use that list to then query each subcollection directly.
这篇关于如何使用 Flutter 获取 Firestore 中每个集合的子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!