I am trying to implement a place where users in my app can search my Firestore Database.

enter image description here

When The user enters a search term into the textField:

return Scaffold(
      appBar: AppBar(
        title: TextField(
          textInputAction: TextInputAction.search,
          onSubmitted: (value) {
            setState(() {
              searchKey = value;
              streamQuery = db
                  .collection('GearLockerItems')
                  .where('searchTerm', isGreaterThanOrEqualTo: searchKey)
                  .where('searchTerm', isLessThan: '${searchKey}z')
                  .snapshots();
            });
          },
          decoration: const InputDecoration(
            hintText: 'Search for Gear',
            prefixIcon: Icon(Icons.search),
          ),
        ),
      )

I take the value for the search term and place it into the streamQuery

I then take that streamQuery and put it into the StreamBuilder:

body: StreamBuilder<dynamic>(
        stream: streamQuery,
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          //widget build for complated call
          print('Inside stream $searchKey');

          if (snapshot.hasData) {
            return ListView.builder(

AS you can see I put a print statement in there for testing and Inside Stream $searchKey keeps showing null, which is was I default it to. I do not understand why when I enter data into the search box its not updating the searchKey to what ever I type and is keeping it null...


Solution 1: Sahil Atahar

First fetch the data from firestore and use then function to set state.May it works and don't forget to use await because you wait untill the data is fetched.


Solution 2: Sahil Atahar

return Scaffold(
appBar: AppBar(
title: TextField(
textInputAction: TextInputAction.search,
onSubmitted: (value) {
searchKey = value;
await db
.collection('GearLockerItems')
.where('searchTerm', isGreaterThanOrEqualTo: searchKey)
.where('searchTerm', isLessThan: '${searchKey}z')
.snapshots().then((data) { setstate((){streamQuery = data; });});
},
decoration: const InputDecoration(
hintText: 'Search for Gear',
prefixIcon: Icon(Icons.search),
),
),
)