问题描述
我想通过将用户ID分配给文档作为字段来将用户相关数据保存在Firestore中。
I want to save user-related data in Firestore by assigning user id to a document as a field.
如何从Firebase Auth获取用户ID?
有没有更好的方法在Firestore中存储用户数据?
我无法通过这种方式从Firebase Auth获取用户ID(Text(_userId)返回_userId ==空错误):
I couldn't get user id from Firebase Auth in this way (the Text(_userId) returns _userId == null error):
String _userId;
...
@override
Widget build(BuildContext context) {
FirebaseAuth.instance.currentUser().then((user) {
_userId = user.uid;
});
return new Scaffold(
appBar: new AppBar(
title: new Text("App bar"),
),
body: new Text(_userId),
);
}
推荐答案
_userId
为空,因为在 FirebaseAuth.instance.currentUser()
返回的Future完成之前就已构建了小部件。完成后为时已晚,小部件也不会更新。一种使用它的方法是使用有点像这样:
_userId
is null because the widgets are being built before the Future returned by FirebaseAuth.instance.currentUser()
has completed. Once it does complete it's too late and the widgets don't update. One way to work with it would be to use a FutureBuilder
somewhat like this:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("App bar"),
),
body: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.uid);
}
else {
return Text('Loading...');
}
},
),
);
}
这篇关于如何从Flutter中的Firebase Auth获取用户ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!