Home > Software design >  Flutter "NoSuchMethodError (NoSuchMethodError: The method 'where' was called on null.
Flutter "NoSuchMethodError (NoSuchMethodError: The method 'where' was called on null.

Time:08-29

I wrote a code like this:

List ProductsList;
//...
void initState() {
  super.initState();
  _firestore.collection("Products").snapshots().listen((event) {
    setState(() {
      ProductsList = event.docs;
    });
  });
}
//...
StreamBuilder(
  stream: ProductsList.where((x) => x["Name"] == SearchText).toList().first, // Filter
  builder: (BuildContext context, snapshot) {
    if (snapshot.hasData) {
      return ListView.builder(
        itemCount: snapshot.data.docs.length,
        itemBuilder: (context, index) {
          return Card(
            child: ListTile(
              title: Text(snapshot.data.docs[index].data()["Name"]),
            ),
          );
        },
      );
    } else {
      return Text("No data");
    }
  }
),

My aim is to fetch the Name value from the Arrays in the list. But when I run the code I get an error like this:

enter image description here

I tested it and the results are in the list. How can I to solve the problem? Thanks for help.

CodePudding user response:

Your ProductsList variable is declared, but not defined. You set the ProductList in the listener in initState, but it only gets set if a change is made in your Products Collection. This is why it can't call the .where on ProductList, because it's null after the initState.

You either give ProductsList a default Value

List ProductList = [];

or you pass the stream into the StreamBuilder and change your logic inside the builder

StreamBuilder(
  stream: _firestore.collection("Products").snapshots(),
  • Related