firebase 尝试获取firestore子集合中的文档数据,然后在flutter上显示此错误“Null check operator used on a null value“?

92dk7w1h  于 2023-02-05  发布在  Flutter
关注(0)|答案(1)|浏览(409)

我试图获取firestore子集合中的文档数据,然后显示此错误“空值上使用了空检查操作符“。我想为每个用户获取用户集合中的一篇文章。

数据库截图
用户表

文章子集

所有文章UI

点击查看按钮时如何获取文章
查看所有文章界面按钮代码

ElevatedButton(child: Text('View'),onPressed: () {                                                
 Navigator.of(context).push(MaterialPageRoute(builder: (context) => ViewOneUserArticleScreen(id: data[index].id,)));

查看一个商品代码

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

模型

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,

};
  }


}

新错误

toiithl6

toiithl61#

问题出在解析方法上,请将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
  );

在你的json中,topicdescriptionurl可能是null,但是你在它们上面使用了!,这意味着你确信它们不是空的,但是它们是空的。同样,你的id可能是空的,但是在你的对象模型中你把它设置为required,因此您需要为其提供默认值,或者只是删除它前面的required

相关问题