Flutter - Can a ListView contain a static widget and a stream

心已入冬 提交于 2020-03-23 03:53:43

问题


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:

  1. If there isn't any documents in the firestore collection, it won't render the static widget.
  2. If the internet connection is slow, it won't render the static widget until the first document is downloaded.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!