简体   繁体   English

从 flutter 中的 firebase firestore 获取当前用户的数据

[英]Getting current user's data from firebase firestore in flutter

I want to get data from firestore, but I can't seem to do it properly and it always returns null.我想从 Firestore 获取数据,但我似乎无法正确执行,它总是返回 null。 Here's what I tried:这是我尝试过的:

Map<String, dynamic>? userMap2;

void getCurrentUser() async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;

final User? user = _auth.currentUser;
final uuid = user!.uid;

setState(() {
  isLoading = true;
});

await _firestore
    .collection('users')
    .where("uid", isEqualTo: uuid)
    .get()
    .then((value) {
  setState(() {
    userMap2 = value.docs[0].data();
    isLoading = false;
  });
  print(userMap2);
});

} }

and when I try to use that data, I try to use it like this: userMap2!['firstName']当我尝试使用该数据时,我尝试像这样使用它: userMap2!['firstName']

Try to put user data in document and then use,尝试将用户数据放入文档中然后使用,

     _firestore
     .collection('users')
     .doc(uuid)
     .get().then((value) {
      setState(() {
      userMap2 = value.docs[0].data();
      isLoading = false;
  });
   print(userMap2);
 });

In React, calling setState is an asynchronous operation.在 React 中,调用setState是一个异步操作。 In addition, loading data from Firestore is an asynchronous operation.此外,从 Firestore 加载数据是一个异步操作。 This means that in your current code, the print(userMap2) runs before your then callback is called, and even further before the userMap2 = value.docs[0].data() has been completed.这意味着在您当前的代码中, print(userMap2)在调用then回调之前运行,甚至在userMap2 = value.docs[0].data()完成之前运行。

I recommend not combining then with await , and doing:我建议不要将thenawait结合使用,并执行以下操作:

const value = await _firestore // 👈
    .collection('users')
    .where("uid", isEqualTo: uuid)
    .get();
setState(() {
  userMap2 = value.docs[0].data();
  isLoading = false;
});
print(value.docs[0].data()); // 👈

On the first line I marked, we're now taking the return value from the await ed get() , so that we no longer need a then block.在我标记的第一行,我们现在从await ed get()返回值,因此我们不再需要then块。 This handles the asynchronous nature of the call to Firestore.这处理了对 Firestore 的调用的异步性质。

Then on the second marked line, we print the value directly from the results from the database, instead of from the setState call.然后在第二个标记的行上,我们直接从数据库的结果中打印值,而不是从setState调用。 This addresses the asynchronous nature of calling setState .这解决了调用setState的异步性质。

For more on these, see:有关这些的更多信息,请参阅:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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