[英]Tried to fetch document data in firestore subcollection then show this error "Null check operator used on a null value "on flutter?
I tried to fetch document data in firestore subcollection then show this error "Null check operator used on a null value ".我尝试在 firestore 子集合中获取文档数据,然后显示此错误“在 null 值上使用了空检查运算符”。 I want to fetch one article in user collection for each users.我想为每个用户获取用户集合中的一篇文章。
database screenshot数据库截图
user table用户表
article subcollection文章子集
all articles UI所有文章用户界面
how to fetch a article when click view button单击查看按钮时如何获取文章
View button code in All articles UI在所有文章 UI 中查看按钮代码
ElevatedButton(child: Text('View'),onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => ViewOneUserArticleScreen(id: data[index].id,)));
view one article code查看一篇文章代码
Articles? oneArticle;
bool loading = false;
@override
initState() {
super.initState();
loading = true;
getArticle();
}
User? user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
Future<void> getArticle() async {
final id = widget.id;
final reference = FirebaseFirestore.instance.doc('users/${user?.uid}/articles/$id');
final snapshot = reference.get();
final result = await snapshot.then(
(snap) => snap.data() == null ? null : Articles.fromJson(snap.data()!));
setState(() {
oneArticle = result;
loading = false;
});
}
model model
class Articles {
final String id;
final String topic;
final String description;
final String url;
Articles({
required this.id,
required this.topic,
required this.description,
required this.url
});
Articles.fromJson(Map<String, dynamic> json)
: this(
id: json['id'],
topic: json['topic']! as String,
url: json['url']! as String,
description: json['description']! as String,
);
Map<String, Object?> toJson() {
return {
'id': id,
'topic': topic,
'url': url,
'description': description,
};
}
}
Your Issue is in your parsing method, change your Articles.fromJson
to this:您的问题出在您的解析方法中,将您的Articles.fromJson
更改为:
Articles.fromJson(Map<String, dynamic> json)
: this(
id: json['id'] ?? '', // <--- change this
topic: json['topic'] as String ?? '', // <--- change this
url: json['url'] as String ?? '', // <--- change this
description: json['description'] as String ?? '', // <--- change this
);
in your json, topic
, description
and url
may be null
but you used !
在你的 json 中, topic
, description
和url
可能是null
但你用过!
on them and that means you are sure that they aren't null but they are.在他们身上,这意味着你确定他们不是 null 但他们是。 Also your id
may be null to but in your object model you set it as required
, so you need to provide default value to it or just remove the required
before it.此外,您的id
可能是 null 到,但在您的 object model 中,您将其设置为required
的,因此您需要为其提供默认值或仅删除它之前的required
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.