【问题标题】:Adding SearchField to StreamBuilder Reading from Firestore将 SearchField 添加到 StreamBuilder 从 Firestore 读取
【发布时间】:2020-01-09 18:01:55
【问题描述】:

我有一个程序,我从 Firebase 的云 Firestore 获取用户列表,并使用 Flutter 中的 StreamBuilder 将它们显示在 Listview 中。用户数量会很大,我想在我的流构建器中实现一个搜索字段,它将查询与我的搜索字段匹配的结果。我希望它看起来像这样:

--图片来源:https://blog.usejournal.com/flutter-search-in-listview-1ffa40956685

我的 Streambuilder 如下所示:

StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance
            .collection('users')
            .snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Center(
                child: Column(
                  children: <Widget>[
                    CircularProgressIndicator(),
                    Text('Loading'),
                  ],
                ),
              );
            default:
              return Container(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListView.separated(
                      shrinkWrap: true,
                      padding: EdgeInsets.all(10.0),
                      itemCount: snapshot.data.documents.length,
                      itemBuilder: (context, index) {
                        return buildUserRow(snapshot.data.documents[index]);
                      },
                      separatorBuilder: (context, index) {
                        return Divider();
                      },
                    ),
                  ],
                ),
              );
          }
        })

所以我想使用这个 StreamBuilder 作为我的数据源,并通过文档快照的'name' 属性进行搜索。非常感谢任何帮助。

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    Firestore 实际上变得很容易

    在字符串字段上添加 if 条件。如果它包含搜索字符串,则返回小部件。

    这不是最终代码,您必须进行许多更改。但这是可以做到的。

    ListView.separated(
            shrinkWrap: true,
            padding: EdgeInsets.all(10.0),
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, index) {
              if (snapshot.data.documents[index].contains(youSearchString))
                return buildUserRow(snapshot.data.documents[index]);
            },
            separatorBuilder: (context, index) {
              return Divider();
            })
    

    【讨论】:

    • 这种方式看起来很生涩,因为每次用户更改文本字段时,都会调用 setState 方法更改 searchString 导致应用程序必须从 firestore 重新加载数据
    • 同样的问题。我希望过滤 StreamBuilder 检索到的数据而不重新创建它。 setState 方法再次触发流查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2020-11-29
    • 2021-09-30
    • 2018-10-14
    • 2019-10-01
    • 2021-03-30
    • 2020-07-30
    相关资源
    最近更新 更多