Problem with stream and firebase Bad state: field does not exist within the DocumentSnapshotPlatform

Issue

I have a StreamBuilder that is meant to be getting me a list of documents from firestore based on a variable being passed through, though I am getting the above error.

StreamBuilder

StreamBuilder<QuerySnapshot>(
          stream: DatabaseService.getFeedPosts(widget.currentUserId),
          builder: (context, snapshot) {
            if (snapshot.hasError) print(snapshot.error);
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    CircularProgressIndicator(),
                    // Loader Animation Widget
                    Padding(padding: const EdgeInsets.only(top: 20.0)),
                    Text('Finding tasks'),
                  ],
                ),
              );
            }
            if (snapshot.hasData) {
              final documents = snapshot.data.docs;

              return ListView(
                  children: documents
                      .map(
                        (doc) => TaskList(
                          currentUserId: widget.currentUserId,
                          task: doc['id'],
                          user: doc['ownerId'],
                        ),
                      )
                      .toList());
            } else if (snapshot.hasError) {
              print('Error');
              return Text('It\'s Error!');
            }
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text('Unable to  find any tasks'),
                ],
              ),
            );
          }),

Firebase query

static Stream<QuerySnapshot> getFeedPosts(String userId) {
    return tasksRef
        .where('authorId', isEqualTo: userId)
        .orderBy('timestamp', descending: true)
        .snapshots();
  }

Solution

You should call data() method from QueryDocumentSnapshot before using the [] operator:

return ListView(
  children: documents
  .map(
    (doc) => TaskList(
      currentUserId: widget.currentUserId,
      task: doc.data()['id'],
      user: doc.data()['ownerId'],
    ),
  )
  .toList(),
);

Answered By – Stewie Griffin

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *