firebase 我如何使用cloud firestore的文档ID访问文档字段?

0dxa2lsx  于 2023-01-02  发布在  其他
关注(0)|答案(2)|浏览(190)

我想从Cloud Firestore访问我的文档字段uname。我使uid和文档ID相同,当我尝试访问文档字段时,它显示错误Bad state: field does not exist within the DocumentSnapshotPlatform

这是我的密码

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

kgqe7b3p1#

您必须使用data()DocumentSnapshot的数据进行get,然后访问uname
尝试将value替换为value.data()
并使用uname进行访问,方法是:value.data()?["uname"]

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

sr4lhrrt2#

get()的返回值实际上是一个DocumentSnapshot,需要访问data()来获取文档字段的Map<String, dynamic>,然后从其中访问"uname"值,如下所示:

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

相关问题