Home > OS >  How can I acess a document field using document id from cloud firestore?
How can I acess a document field using document id from cloud firestore?

Time:01-01

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(()),
    );
  }

CodePudding user response:

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"]));

CodePudding user response:

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 need to access the name field
      });
  • Related