Home > front end >  Flutter Firebase Problems with Query Firestore and Streambuilder()
Flutter Firebase Problems with Query Firestore and Streambuilder()

Time:08-24

I am trying to search for documents matching the text in the TextField and display them with a Streambuilder. Since I am a flutter beginner, I didn't find helpful videos and tutorials on how to do that.

I'm trying to do something like that:

Widget body(BuildContext context) {
    if(textControllerSearch.text != "") {
      if(textFocusNodeSearch.hasFocus == false) {
        return ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(15)),
          child: StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection('users')
                  .doc(firebaseUser!.uid.toString())
                  .collection("recipes")
                  .where("recipeName", arrayContains: textControllerSearch.text.trim())
                  .limit(3)
                  .snapshots(),
            builder: (context, snapshot) {
              return ListView.builder(
                  itemCount: snapshot.data!.docs.length,
                  itemBuilder: (context, index) {
                    DocumentSnapshot documentSnapshot = snapshot.data!.docs[index];
                    return ListTile(title: Text(documentSnapshot['recipeName']));
                  });
            },
          ),
        );
      } else {
        return Container(
          alignment: Alignment.topCenter,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                child: Lottie.asset("assets/lottie/search_bubble.json", width: MediaQuery.of(context).size.width * 0.5, fit: BoxFit.fitWidth),
              ),
              Container(
                child: Text(
                  "Searching...",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Color(0xFFEC8E00).withOpacity(0.5),
                    fontSize: 10,
                  ),
                ),
              ),
            ],
          ),
        );
      }
    } else {
      return Container();
    }
  }

The TextField:

TextFormField(
                                      focusNode: textFocusNodeSearch,
                                      textAlign: TextAlign.left,
                                      keyboardType: TextInputType.name,
                                      controller: textControllerSearch,
                                      autofocus: true,
                                      onFieldSubmitted: (value) {
                                        setState(() {});
                                      },
                                      onChanged: (value) {
                                        if(textControllerSearch.text.trim() == "") {
                                          setState(() {
                                            notSearching = true;
                                          });
                                        } else {
                                          setState(() {
                                            notSearching = false;
                                          });
                                        }
                                      },
                                      style: TextStyle(
                                        fontFamily: 'Font',
                                        fontSize: 16,
                                        color: Colors.white.withOpacity(0.75),
                                      ),
                                      obscureText: false,
                                      cursorColor: Color(0xFFEC8E00),
                                      decoration: InputDecoration(
                                        border: InputBorder.none,
                                        hintText: 'Search',
                                        hintStyle: TextStyle(
                                          fontSize: 14,
                                          color: Colors.white.withOpacity(0.75),
                                          fontFamily: 'Font',
                                        ),
                                      ),
                                    ),

I get this error but I am not able to clearly understand what is the error and what is causing the problem:

The following _CastError was thrown building StreamBuilder<QuerySnapshot<Object?>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Object?>, AsyncSnapshot<QuerySnapshot<Object?>>>#6bf78):
Null check operator used on a null value

CodePudding user response:

Accoreding to your log, error is somewhere here:

 child: StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection('users')
                  .doc(firebaseUser!.uid.toString())
                  .collection("recipes")
                  .where("recipeName", arrayContains: textControllerSearch.text.trim())
                  .limit(3)
                  .snapshots(),
            builder: (context, snapshot) {
              return ListView.builder(
                  itemCount: snapshot.data!.docs.length,
                  itemBuilder: (context, index) {
                    DocumentSnapshot documentSnapshot = snapshot.data!.docs[index];
                    return ListTile(title: Text(documentSnapshot['recipeName']));
                  });

You set ! on snapshot.data, check if snapshot.data is different from null.

CodePudding user response:

this is because there is a null value somewhere. try replacing

 return ListView.builder(
                  itemCount: snapshot.data!.docs.length,
                  itemBuilder: (context, index) {
                    DocumentSnapshot documentSnapshot = snapshot.data!.docs[index];
                    return ListTile(title: Text(documentSnapshot['recipeName']));
                  });

with snapshot.data?.docs[index];

CodePudding user response:

child: StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection('users')
                  .doc(firebaseUser!.uid.toString())
                  .collection("recipes")
                  .where("recipeName", arrayContains: textControllerSearch.text.toString().trim()) //add toString()
                  .limit(3)
                  .snapshots(),
            builder: (context, snapshot) {
              return ListView.builder(
                  itemCount: snapshot.data!.docs.length,
                  itemBuilder: (context, index) {
                    DocumentSnapshot documentSnapshot = snapshot.data!.docs[index];
                    return ListTile(title: Text(documentSnapshot['recipeName'].toString())); //add toString()
                  });
  • Related