Adding SearchField to StreamBuilder Reading from Firestore

给你一囗甜甜゛ 提交于 2021-02-08 15:04:57

问题


I have a program that I get a list of users from Firebase's cloud Firestore, and display them in a Listview using a StreamBuilder in Flutter. The number of users will be large, and I want to implement a search field in my streambuilder that will query results that match my search field. I want it to look like this:

--photo credit: https://blog.usejournal.com/flutter-search-in-listview-1ffa40956685

My Streambuilder that looks like the following:

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

So I want to use this StreamBuilder as my data source, and search by the Document Snapshot's 'name' property. Any help is greatly appreciated.


回答1:


It actually gets easy with Firestore

Add if condition on the string field. If it contains the search string, return widget.

This is not the final code, you will have to make many changes. But this is how it can be done.

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();
        })


来源:https://stackoverflow.com/questions/57829119/adding-searchfield-to-streambuilder-reading-from-firestore

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