[英]How to get data from the firebase and store it into a list for futher manipulation in dart
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.我有一个名为 subject 的 class,它具有属性/成员 courseCode、courseIcon,最后是 subjectName。 Everything is okay so far, but vs code is saying:
到目前为止一切都很好,但是 vs code 说:
Type: dynamic
类型:动态
The property 'docs' can't be unconditionally accessed because the receiver can be 'null'.
不能无条件地访问属性“docs”,因为接收者可以是“null”。 Try making the access conditional (using '?.') or adding a null check to the target ('.')."
尝试使访问有条件(使用 '?.')或向目标('.')添加 null 检查。”
I have already imported all the necessary libraries, as well as vs code's reccomendations.我已经导入了所有必要的库,以及 vs 代码的推荐。 What should I try?
我应该尝试什么?
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:该错误意味着
snapshot.data
可能是null
,因此您需要先验证它不是 null ,然后才能将其分配给不可为 null 的docs
变量:
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
.本地
querySnapshot
变量在if
块内保证为非空,因此现在您可以简单地将querySnapshot.docs
分配给docs
。
I also removed the .data()
calls, as @Gwhyyy pointed out in their comment.正如@Gwhyyy 在他们的评论中指出的那样,我还删除了
.data()
调用。
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.您可能想花点时间阅读Dart中的可空性,因为您可能会遇到更多类型根据处理 null 发生变化的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.