问题
Currently my I have a ListView that is warped by a StreamBuilder which gets data from firebase firestore (e.g a list of users). This is how it looks:
Widget UsersList = new StreamBuilder(
stream: Firestore.instance
.collection('users')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text("loading");
return new ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
_buildItem(context, snapshot.data.documents[index]),
);
}
);
The question is how to add to the top of the ListView a static widget (e.g. a button to create a new user), I don't want the button to stay on the top of the page all the time, it should scroll with the ListView.
A workaround: in the _buildItem() function I could receive a boolean if it is the first document (by passing to the function index==0), and if true build the static widget (e.g. the add user button) first. But I can think of three problems:
- If there isn't any documents in the firestore collection, it won't render the static widget.
- If the internet connection is slow, it won't render the static widget until the first document is downloaded.
- It is a workaround...
回答1:
You could check the length inside the ListView.builder
and always add an item for the button.
Widget UsersList = new StreamBuilder(
stream: Firestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
return new ListView.builder(
itemCount: (snapshot?.data?.documents?.length ?? 0) + 1,
itemBuilder: (context, index) {
if (index == 0)
return FlatButton(child: Text("Add"));
else
_buildItem(context, snapshot.data.documents[index-1]);
},
);
},
),
来源:https://stackoverflow.com/questions/52686163/flutter-can-a-listview-contain-a-static-widget-and-a-stream