方法'[]'在null上被调用颤抖?

问题描述

我的futurebuilder发生错误,上面的任何人都没有任何解决方案相关的引起错误的小部件是: FutureBuilder ................................................. ................................................... ................................................... ................................................... ................................................... ........ ..........................

noti.dart
          Widget build(BuildContext context) {
            return FutureBuilder(
                future: postReference
                    .document(userId)
                    .collection("usersPosts")
                    .document(postId)
                    .get(),builder: (context,datasnapshot) {
                  if (!datasnapshot.hasData) {
                    return circularProgress();
                  }
                  Post post = Post.fromDocument(datasnapshot.data);
                  return Center(
                    child: Scaffold(
                      appBar: header(context,strTitle: post.description),body: ListView(
                        children: <Widget>[
                          Container(
                            child: post,),],);
                });


    Post.dart

class Post extends StatefulWidget {
  final String postId;
  final String ownerId;
  // final String timestamp;
  final dynamic likes;
  final String username;
  final String description;
  final String location;
  final String url;
  //
  Post({
    this.postId,this.ownerId,// this.timestamp,this.likes,this.username,this.description,this.location,this.url,});

  factory Post.fromDocument(DocumentSnapshot documentSnapshot) {
    return Post(
      postId: documentSnapshot["postId"],ownerId: documentSnapshot["ownerId"],likes: documentSnapshot["likes"],// timestamp: documentSnapshot["timestamp"],username: documentSnapshot["username"],description: documentSnapshot["description"],location: documentSnapshot["location"],url: documentSnapshot["url"],);
  }

引用它的post方法

displayPost(context) {
  Navigator.push(
    context,MaterialPageRoute(
      builder: (context) => PostScreen(
        postId: postId,userId: userId,);
}

解决方法

这可能是因为您从查询中接收到空值。 您想要将documentSnapshot [“ postId”]映射到您的Post,并且此事件由于null而失败。

对于纯净代码,我建议您使用quicktype创建一个新的Post模型 并用json映射您的帖子。 然后检查value == null:

factory Score.fromJson(Map<String,dynamic> json) => Score(
    score: json["score"] == null ? null : json["score"].toDouble(),