1
List<DocumentSnapshot> docs = snapshot.data.docs; _selectedSubjects = docs .map( (doc) => Subject( doc['SubjectName'].data(), doc['courseIcon'].data(), doc['courseCode'].data(), ), ) .toList(); 

I have a class called subject that has attributes/members courseCode, courseIcon, and lastly subjectName. Everything is okay so far, but vs code is saying:

Type: dynamic

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 ('!')."

I have already imported all the necessary libraries, as well as vs code's reccomendations. What should I try?

1 Answer 1

2

The error means that snapshot.data may be null, so you need to first verify that it's not null before you can assign it to your non-nullable docs variable:

var querySnapshot = snapshot.data; if (querySnapshot != null) { List<DocumentSnapshot> docs = querySnapshot.docs; _selectedSubjects = docs .map( (doc) => Subject( doc['SubjectName'], doc['courseIcon'], doc['courseCode'], ), ) .toList(); } 

The local querySnapshot variable is guaranteed to be non-null inside the if block, so now you can simply assign querySnapshot.docs to docs.

I also removed the .data() calls, as @Gwhyyy pointed out in their comment.

You might want to take a moment to read up on nullability in Dart as you're likely to encounter many more situations where the type changes based on handling null.

Sign up to request clarification or add additional context in comments.

3 Comments

I guess there is another error in trying to get fields as this doc['SubjectName'].data()
I have followed your instructions and thanks for the link on nullability in Dart. I did learn a lot. However I am still getting an error. A different one this time around "Type: dynamic 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'."
Never mind I have fixed the new error got help from an answer on stack overflow.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.