0
votes

After migrating to null safety getting error The getter 'docs' isn't defined for the type 'AsyncSnapshot<Object?>'. Try importing the library that defines 'docs', correcting the name to the name of an existing getter, or defining a getter or field named 'docs'.

Code snippet where error is

    return FutureBuilder(
      future: searchResultsFuture,
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return circularProgress();
        }
        List<UserResult> searchResults = [];
        snapshot.docs.forEach((doc) {    //have error here
          User user = User.fromDocument(doc);
          UserResult searchResult = UserResult(user);
          searchResults.add(searchResult);
        });
        return ListView(
          children: searchResults,
        );
      },
    );
  } 

searchResultsFuture


  handleSearch(String query) {
    Future<QuerySnapshot> users =
        usersRef.where("displayName", isGreaterThanOrEqualTo: query).get();
    setState(() {
      searchResultsFuture = users;
    });
  }

  clearSearch() {
    searchController.clear();
  }
2
"The getter 'docs' isn't defined for the type 'AsyncSnapshot<Object?>" - yes indeed AsyncSnapschot does not have a field called docs - pskink
so what do i have to do to fix my code? - Maldives Hunt
use AsyncSnapshot.data property - pskink
@pskink can you please tell how i can use AsyncSnapshot.data property here - Maldives Hunt
what do you see if you call print(snapshot.data)? if it is not null then it has your data - pskink

2 Answers

1
votes

The snapshot in your code is an AsyncSnapshot, which indeed doesn't have a docs child. To get the docs from Firestore, you need to use:

snapshot.data.docs

Also see the FlutterFire documentation on listening for realtime data, which contains an example showing this - and my answer here explaining all snapshot types: What is the difference between existing types of snapshots in Firebase?

0
votes

usually, it takes a few ms for data to retrieve so I tried this to make sure my operations are performed after data is retrieved

return StreamBuilder<QuerySnapshot>(
    stream: Collectionreference
        .snapshots(),
    builder: (BuildContext context,
        AsyncSnapshot<QuerySnapshot> activitySnapshot) {
      if (activitySnapshot.hasError) {
        return  Center(
              child: Text('Something went wrong'),
            );
      }
      if (activitySnapshot.connectionState == ConnectionState.waiting) {
        return Center(
                child: SpinKitWave(
              color: constants.AppMainColor,
              itemCount: 5,
              size: 40.0,
            )));
      }
      if (!activitySnapshot.hasData || activitySnapshot.data.docs.isEmpty) {
        return Center(
              child: Text('Nothing to Display here'),
            );
      }
      if (activitySnapshot.hasData) {
         activitySnapshot.data.docs.forEach(doc=>{
            print(doc);
          })
      }
     }
   });