我已经尝试了一周,搜索并更改了我的代码,但我无法让它工作.. 我想在堆栈中创建一个widget列表,并尝试了很多方法。以下是使用forEach方法和StreamBuilder方法的测试代码:
方法1:
class Recordlist extends StatelessWidget {
@override
Widget build(BuildContext context) {
Firestore.instance.collection('records').document(uid).collection("pdrecords").getDocuments().then( (querySS) {
querySS.documents.forEach( (doc) {
return new Container();
});
}).catchError( (e) {
return new Container();
});
}
}
以上抱怨该函数永远不会返回小部件
方法2:
class Recordlist extends StatelessWidget {
@override
Widget build(BuildContext context) {
Double count = 0.5;
return new StreamBuilder <QuerySnapshot>(
stream: Firestore.instance.collection('records').document(uid).collection("pdrecords").snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
//final int recordCount = snapshot.data.documents.length;
if (snapshot.hasData) {
final int recordCount = snapshot.data.documents.length;
print("got data. records: $recordCount");
if (recordCount >0) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('');
case ConnectionState.waiting: return new Text('Fetching data ...');
case ConnectionState.active: {
count = count + 1.0; print("count: $count");
return new ListPDRecord(
margin: new EdgeInsets.only(bottom: 10.0) * count, // listSlidePosition * 5.5,
width: listTileWidth.value,
title: snapshot.data.documents.elementAt(0)['starttime'],
subtitle: snapshot.data.documents.elementAt(0)['endtime'],
image: nodata,
);
}
break;
case ConnectionState.done: return new Text('Done:');
}
} else {
return noDataListData(
listSlidePosition: listSlidePosition,
listTileWidth: listTileWidth,
);
}
}
}
无论Firebase数据库中有多少项,此方法始终显示1个项目。我怀疑它正在返回相同的位置,因此它有许多物品堆叠在一起。
我真的很困惑。真的很感激一些帮助。
答案 0 :(得分:1)
你只建了一次。您必须将快照中的每个文档都映射到窗口小部件。 Firebase的做法如下。
StreamBuilder(
stream: Firestore.instance
.collection('flutter-posts')
.orderBy('postTime', descending: true)
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData)
return const Center(child: CircularProgressIndicator());
return ListView(
padding: const EdgeInsets.only(top: 8.0),
children:
snapshot.data.documents.map((DocumentSnapshot document) {
return SinglePost(
document: document,
currentUID: appState.firebaseUser.uid,
);
}).toList(),
);
},
),