The getter 'docs' isn't defined for the type 'AsyncSnapshot<Object?>'

Issue

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();
  }

Solution

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?

Answered By – Frank van Puffelen

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *