简体   繁体   中英

Flutter "NoSuchMethodError (NoSuchMethodError: The method 'where' was called on null." Error

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:

在此处输入图像描述

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

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(),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM