Search code examples
flutterfirebasegoogle-cloud-firestorestream-builder

Issue is in changing index of image


if I want to search for kitchen if kitchen is in 9th index and when it is searched its name will bein first index but the image remain same of first index (first index=tea)and text update to kitchen but when i click on kitchen it give the detail of tea How to solve it according to my code. Inshort, the text in the search bar updates correctly, but the url of a image and product details displayed on the screen do not update accordingly. Please solve my issue.

My text field

TextFormField(
                keyboardType: TextInputType.text,
                textInputAction: TextInputAction.search,
                controller: searchcontroller,
                focusNode: fousnode,
        onChanged: (query) {
          setState(() {

            FirebaseFirestore.instance
                .collectionGroup("Add_product")
                .where("product_name", isGreaterThanOrEqualTo: query)
                .where("product_name", isLessThan: query + 'z')
                .snapshots();
          });
        },

                decoration: InputDecoration(
                  hintText: "Search Product",
suffixIcon: widget.enableFocusMode? IconButton(
  icon: Icon(Icons.clear),
  onPressed: () {
    searchcontroller.clear();
  },
)
                        : null,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(11)),
                  ),
                ),
              )

Retrive data

StreamBuilder(
              stream:
              FirebaseFirestore.instance.collectionGroup("Add_product").snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                      child: LoadingAnimationWidget.staggeredDotsWave(
                          color: Colors.red, size: 10));
                }

                List<QueryDocumentSnapshot> data = snapshot.data!.docs;
                if (searchcontroller.text.isNotEmpty) {
                  data = data.where((doc) => doc["product_name"]
                      .toLowerCase()
                      .contains(searchcontroller.text.toLowerCase()))
                      .toList();
                }

UI of app

GridView.builder(
                  shrinkWrap: true,
                  physics: ClampingScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 1,
                    childAspectRatio: 9.0,
                    mainAxisSpacing: 8.0,
                    crossAxisSpacing: 2.0,
                  ),
                  itemCount:data.length,
                  itemBuilder: (itemBuilder, index) {
                    final product = data[index]["product_name"];
                    final searchValue = searchcontroller.text.toLowerCase();
                    final searchIndex = product.toLowerCase().indexOf(searchValue);
                    final searchLength = searchValue.length;
                      return Container(
                        child: InkWell(
                          onTap: (){
                            Navigator.push(context, MaterialPageRoute(builder: (builder)=>detail(
                              url: snapshot.data!.docs[index]["url"],
                              productName: snapshot.data!.docs[index]["product_name"],
                              productPrice: snapshot.data!.docs[index]["product_price"],
                            )));
                            final user = FirebaseAuth.instance.currentUser;
                            if (user != null) {
                              FirebaseFirestore.instance.collection('search_history').add({
                                'searchTerm': snapshot.data!.docs[index]["product_name"],
                                'userId': user.uid,
                                'timestamp': Timestamp.now(),
                              });
                            }
                          },
                          child: ListTile(
                            leading: CircleAvatar(
                              backgroundImage: NetworkImage(
                                  snapshot.data!.docs[index]["url"]
                              ),
                            ),
                            title: RichText(
                              text: TextSpan(
                                text: product.substring(0, searchIndex),
                                style: TextStyle(color: Colors.black),
                                children: [
                                  TextSpan(
                                    text: product.substring(searchIndex, searchIndex + searchLength),
                                    style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
                                  ),
                                  TextSpan(
                                    text: product.substring(searchIndex + searchLength),
                                    style: TextStyle(color: Colors.black),
                                  ),
                                ],
                              ),
                            ),

                          ),
                        ),
                      );

                  },
                );

Solution

  • In InkWell onTap replace index with searchIndex at three places(url, productName, productPrice):

    Navigator.push(context, MaterialPageRoute(builder: (builder)=>detail(
                                  url: snapshot.data!.docs[searchIndex ]["url"],
                                  productName: snapshot.data!.docs[searchIndex ]["product_name"],
                                  productPrice: snapshot.data!.docs[searchIndex ]["product_price"],
                                )));
    

    In leading CircleAvatar NetworkImage index with searchIndex :

    child: ListTile(
                                leading: CircleAvatar(
                                  backgroundImage: NetworkImage(
                                      snapshot.data!.docs[searchIndex]["url"]
                                  ),
                                )