Search code examples
flutterdartnosuchmethoderror

The method '[]' was called on null. Flutter


This is the FutureBuilder:

@override
Widget build(BuildContext context) {
  return FutureBuilder(
    future: postsRef
        .document(userId)
        .collection('userPosts')
        .document(postId)
        .get(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return circularProgress();
      }
      Post post = Post.fromDocument(snapshot.data);
      return Center(
        child: Scaffold(
          appBar: header(context, titleText: post.description),
          body: ListView(
            children: <Widget>[
              Container(
                child: post,
              )
            ],
          ),
        ),
      );
    },
  );
}

The show post method that refers to it:

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

Getting below error

The method '[]' was called on null. Receiver: null Tried calling: The relevant error-causing widget was: FutureBuilder file:///home/testflutter/AndroidStudioProjects/testingflutter/lib/pages/post_screen.dart:15:12


Solution

  • Check the ConnectionState of the snapshot to see if it's done.

    Widget build(BuildContext context) {
      return FutureBuilder(
        future: postsRef
            .document(userId)
            .collection('userPosts')
            .document(postId)
            .get(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting)
            return circularProgress();
          else if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData && snapshot.data.isNotEmpty) {
              Post post = Post.fromDocument(snapshot.data);
              return Center(
                child: Scaffold(
                  appBar: header(context, titleText: post.description),
                  body: ListView(
                    children: <Widget>[
                      Container(
                        child: post,
                      ),
                    ],
                  ),
                ),
              );
            } else {
              return Center(child: Text("No data or it's empty"));
            }
          } else {
            return Center(child: Text("Neither waiting or done..."));
          }
        },
      );
    }
    

    I have fixed up the code to make it easy and added else clauses.