简体   繁体   中英

Flutter: Bad state: field does not exist within the DocumentSnapshotPlatform | cloudfirestore

I am trying to fetch data from the cloud filestore to a Text widget. I did fetch Querysnapshot document data from cloud firestore and show that data in the text widget. but it shows the mentioned error.

body: SafeArea(
    child: SingleChildScrollView(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          StreamBuilder<QuerySnapshot>(
            stream: _firestore.collection('messages').snapshots(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final messages = snapshot.data!.docs;
                List<Text> messageWidgets = [];
                for (var message in messages) {
                  final messageText = message.get('text');
                  final senderText = message.get('sender');

                  final messageWidget = Text('$messageText from $senderText');

                  messageWidgets.add(messageWidget);
                }
                return Column(
                  children: messageWidgets,
                );
              }
              return Text("No widget to build");
            },
          ),
          Container(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(child: TextField(
                  onChanged: (value) {
                    messageText = value;
                  },
                )),
                ElevatedButton(
                  onPressed: () {
                    _firestore.collection('messages').add(
                        {'text': messageText, 'sender': LoggedInUser.email});
                  },
                  child: Text("Send"),
                )
              ],
            ),
          )
        ],
      ),
    ),
  ),

I am able to print the data by using:

 Print(message.data());

How do I resolve this?

The error you mentioned in the title says it all: some of your data probably is missing some fields you're looking for.

I can see you're extracting the text and sender keys. This means that for some message in your loop, ie for some document in your Firestore database, one of those two keys is missing.

As you said, use print(message.data()); to investigate where and why.

Just be sure to put that print statement just below the if(snapshot.hasData) so that you will print to the console before it throws the BadState exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM