简体   繁体   English

Flutter - ListView可以包含静态小部件和流

[英]Flutter - Can a ListView contain a static widget and a stream

Currently my I have a ListView that is warped by a StreamBuilder which gets data from firebase firestore (eg a list of users). 目前我有一个由StreamBuilder扭曲的ListView,它从firebase firestore获取数据(例如用户列表)。 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 (eg 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. 问题是如何在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 (eg the add user button) first. 解决方法:在_buildItem()函数中,如果它是第一个文档(通过传递给函数index == 0),我可以接收一个布尔值,如果是,则首先构建静态小部件(例如添加用户按钮)。 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. 如果firestore集合中没有任何文档,则不会呈现静态窗口小部件。
  2. If the internet connection is slow, it won't render the static widget until the first document is downloaded. 如果Internet连接速度很慢,则在下载第一个文档之前,它不会呈现静态窗口小部件。
  3. It is a workaround... 这是一个解决方法......

You could check the length inside the ListView.builder and always add an item for the button. 您可以检查ListView.builder的长度,并始终为该按钮添加项目。

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]);
      },
    );
  },
),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM