0

When I use this code:

return FutureBuilder(
  future: searchResultsFuture,
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return cargandoCircular();
    }

    List<UserResult> searchResults = [];
    snapshot.data.docs.forEach((doc) {
      User user = User.fromDocument(doc);
      UserResult searchResult = UserResult(user);
      searchResults.add(searchResult);
    });
 return ListView(
      children: searchResults,
    );

I get the error:

The property 'docs' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').

Adding the null check doesn't solve anything, also everything is declared in a User class on another dart file, like this:

class User {
final String id;
final String username;
final String email;
final String photoUrl;
final String displayName;
final String bio;

User(
  {required this.id,
  required this.username,
  required this.email,
  required this.photoUrl,
  required this.displayName,
  required this.bio});

factory User.fromDocument(DocumentSnapshot doc) {
return User(
  id: doc['id'],
  email: doc['email'],
  username: doc['username'],
  photoUrl: doc['photoUrl'],
  displayName: doc['displayName'],
  bio: doc['bio'],
);}}
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
  • add a ! to snapshot.data.docs.forEach((doc): snapshot.data!.docs.forEach((doc) – Sajad Abdollahi Jul 11 '21 at 20:13
  • I clarified in the question that adding the null check didn't solve anything. –  Jul 11 '21 at 20:22
  • 2
    Does this answer your question? [The property 'docs' cannot be unconditionally accessed because received can be 'null' Flutter](https://stackoverflow.com/questions/66670247/the-property-docs-cannot-be-unconditionally-accessed-because-received-can-be) – Pit Jul 12 '21 at 07:22
  • I added the type to the FutureBuilder, and the ? on snapshot.data, and it solves the error in vs code but it doesn't do anything on the app. –  Jul 12 '21 at 11:07

1 Answers1

1

access it using this:

snapshot.data?.docs

since the data from snapshot can be null and that is why we check in future builder for whether snapshot.hasData is true or not.

Nandan Wewhare
  • 445
  • 5
  • 11
  • When I add the ? it throws this error: The getter 'docs' isn't defined for the type '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'. –  Jul 12 '21 at 10:40
  • Try snapshot?.data.docs – Nandan Wewhare Jul 12 '21 at 11:37