【问题标题】:Flutter- the method [] was called on nullFlutter-方法[]在null上被调用
【发布时间】:2021-09-23 20:49:42
【问题描述】:

我一直在关注如何构建类似于 Instagram 的社交媒体应用程序的教程,虽然我的代码与教程中的代码相同,但在尝试显示用户的帖子时出现此错误:

以下 NoSuchMethodError 被抛出构建 FutureBuilder(dirty, state: _FutureBuilderState#0c840): 方法 '[]' 在 null 上被调用。接收者:null 尝试调用:

相关的导致错误的小部件是:FutureBuilder file:///Users/Michael/Desktop/Flutter%20Projects/greenroom/lib/pages/PostScreenPage.dart:19:12 抛出异常时,这是堆栈:#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5) #1 文档快照。[] (包:cloud_firestore/src/document_snapshot.dart:29:42)#2 新 Post.fromDocument(包:buddiesgram/widgets/PostWidget.dart:36:31) #3 PostScreenPage.build。 (包:buddiesgram/pages/PostScreenPage.dart:26:26)#4 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:751:55)

这是 FutureBuilder:

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: postsReference.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,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

这是帖子:

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

【问题讨论】:

    标签: firebase flutter android-studio dart


    【解决方案1】:

    尝试检查该值是否为空

    if(dataSnapshot.data == null || !dataSnapshot.hasData){
      return circularProgress();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 2020-06-12
      • 2020-06-07
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      相关资源
      最近更新 更多