Reputation: 1033
I have tried for a week, searching and changing my code but I just cannot get it to work.. I want to create a list of widget inside a stack and have tried many methods. The following is my test code using forEach method and StreamBuilder methods:
Method 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();
});
}
}
The above complains that the function never returns a widget
Method 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,
);
}
}
}
This method always show 1 item no matter how many items I have in the Firebase database. I suspect it is returning the same position so it has many items stacked on top of each other.
I am getting really confused. Really appreciate some help.
Upvotes: 0
Views: 745
Reputation: 1360
You are building only one time. You have to take each document in the snapshot and map it to a widget. Firebase way of doing it is below.
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(),
);
},
),
Upvotes: 1