skip to Main Content

I want to access my document field uname from cloud firestore . I made the uid and document id same and when I tried to access the document field it shows the error Bad state: field does not exist within the DocumentSnapshotPlatform

enter image description here

This is my code

  
class test extends StatefulWidget {
  const test({Key? key}) : super(key: key);
  _testState createState() => _testState();
}

class _testState extends State<test> {
 

  final userData = FirebaseFirestore.instance
      .collection("Users")
      .doc(FirebaseAuth.instance.currentUser!.uid)
      .get()
      .then((value) => print((value.data() ? ["uname"])));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text(()),
    );
  }

2

Answers


  1. the return of get() is actually a DocumentSnapshot, you need to access the data() to get the Map<String, dynamic> of your document’s fields, then access the "uname" value from it like this:

    final userData = FirebaseFirestore.instance
          .collection("Users")
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .get()
          .then((value)  {
          final documentData = value.data() as Map<String, dynamic>; // this is your document data           
          print(documentData["uname"]) // this is you what need to access the name field
          });
    
    Login or Signup to reply.
  2. You’ll have to get the data of the DocumentSnapshot using data() and then access the uname.

    Try to replace value with value.data()

    And access using uname using: value.data()?["uname"]

    final userData = FirebaseFirestore.instance
          .collection("Users")
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .get()
          .then((value) => print((value.data()?["uname"]));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search