我在这里非常困惑……如果我需要执行文档(在哪里)查询,使用FutureBuilder从Firestore中列出数组的正确语法是什么?
Firestore数据库结构:
- [companies]
- [doc]
- [gallery]
- [doc]
- [reference] <- (ie, companies/doc)
- [gallery_images] // List these, but show only images that match where() query
这是我当前的代码:
Future<List<dynamic>> getGallery() async {
var firestore = Firestore.instance;
DocumentReference docRef = firestore.collection('companies').document(widget.docID);
var ref = firestore.collection('galleries').where('companyRef', isEqualTo: docRef).getDocuments();
return ref.get().then((datasnapshot) {
if (datasnapshot.exists) {
List<dynamic> imageArray = datasnapshot.data['gallery_images'].toList();
return imageArray;
} else {
print("Please just work...");
}
},
);
}
FutureBuilder(
future: getGallery(),
builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text("Loading..."),
);
} else {
return GridView.builder(
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount: *length*,
itemBuilder: (BuildContext context, int index) {
return ViewGalleryItemThumbnail(
viewGalleryItem: snapshot.data[index],
....
如果有人可以告诉我我要去哪里错了,我将不胜感激!
答案 0 :(得分:0)
尚不清楚您的Cloud Firestore模式是什么样,但这似乎更有可能返回正确的动态列表。 (请注意,通过向地图添加通用名称,您可以返回特定列表,例如.map<SomeRealType>((snap) => snap.data['gallery_images'])
。)
当您坚持使用FutureBuilder
时,暂时恢复为有状态的小部件有时会很有用。覆盖initState
,并调用经过稍微修改的getGallery
,该变量最后不返回值,而是将其分配给setState
内部的成员变量。这样,打印语句的机会就很多。另外,尝试将异步函数中的任何.then
转换为线性await
的序列。它使读取变得更容易(并且调试打印以合理的线性顺序出现)。
Future<List<dynamic>> getGallery() async {
var firestore = Firestore.instance;
var docRef = firestore.collection('companies').document(widget.docID);
var querySnap = await firestore
.collection('galleries')
.where('companyRef', isEqualTo: docRef)
.getDocuments();
return querySnap.documents
.map((snap) => snap.data['gallery_images'])
.toList();
}