george derderian
george derderian

Reputation: 173

flutter Bad state: field does not exist within the DocumentSnapshotPlatform

When i build my app and i signup a new user and go to the chatting screen i am getting this exception: Exception caught by widgets library The following StateError was thrown building: Bad state: field does not exist within the DocumentSnapshotPlatform so what can i do? this is the new message file:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class NewMessages extends StatefulWidget {
 @override
 NewMessagesState createState() => NewMessagesState();
}

class NewMessagesState extends State<NewMessages> {
 final controller = TextEditingController();
 String enteredmessage = '';

 sendmessage() async {
   FocusScope.of(context).unfocus();
   final user = FirebaseAuth.instance.currentUser;
   final userdata = await FirebaseFirestore.instance
       .collection('users')
       .doc(user!.uid)
       .get();
   FirebaseFirestore.instance.collection('chat').add({
     'text': enteredmessage,
     'created at': Timestamp.now(),
     'username': userdata['username'],
     'userid': user.uid,
   });
   controller.clear();
 }

 @override
 Widget build(BuildContext context) {
   return Container(
       margin: EdgeInsets.only(top: 8),
       padding: EdgeInsets.all(8),
       child: Row(
         children: [
           Expanded(
               child: TextField(
             controller: controller,
             decoration: InputDecoration(labelText: "send a message..."),
             onChanged: (val) {
               setState(() {
                 enteredmessage = val;
               });
             },
           )),
           IconButton(
               color: Theme.of(context).primaryColor,
               onPressed: 
                   enteredmessage.trim().isEmpty ? null : sendmessage,
               icon: Icon(Icons.send))
         ],
       ));
 }
}


and this is the messages file:

import 'package:app1/chat/message_bubble.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Messages extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return StreamBuilder<QuerySnapshot>(
     stream: FirebaseFirestore.instance
         .collection('chat')
         .orderBy('created at', descending: true)
         .snapshots(),
     builder: (ctx, snapShot) {
       if (snapShot.connectionState == ConnectionState.waiting) {
         return CircularProgressIndicator();
       }

       final docs = snapShot.data!.docs;
       final user = FirebaseAuth.instance.currentUser;
       return ListView.builder(
         reverse: true,
         itemCount: docs.length,
         itemBuilder: (ctx, index) => Message_bubble(
           docs[index]['text'],
           docs[index]['username'],
           docs[index]['userid'] == user!.uid,
           ValueKey(docs[index]['userid']),
         ),
       );
     },
   );
 }
}


and that is the messagebubble file:


import 'package:app1/chat/message_bubble.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Messages extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance
          .collection('chat')
          .orderBy('created at', descending: true)
          .snapshots(),
      builder: (ctx, snapShot) {
        if (snapShot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }

        final docs = snapShot.data!.docs;
        final user = FirebaseAuth.instance.currentUser;
        return ListView.builder(
          reverse: true,
          itemCount: docs.length,
          itemBuilder: (ctx, index) => Message_bubble(
            docs[index]['text'],
            docs[index]['username'],
            docs[index]['userid'] == user!.uid,
            ValueKey(docs[index]['userid']),
          ),
        );
      },
    );
  }
}

Upvotes: 0

Views: 311

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598797

I think to access the fields of the document, you now need to access them through data(), so:

userdata.data()['username']

Upvotes: 1

Related Questions