Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding SearchField to StreamBuilder Reading from Firestore

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.

like image 504
Gabe Avatar asked Nov 07 '22 14:11

Gabe


1 Answers

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();
        })
like image 135
Deep Shah Avatar answered Nov 11 '22 08:11

Deep Shah