Sab*_*han 2 dart firebase firebase-authentication flutter
我正在尝试-
final Future<FirebaseUser> user = auth.currentUser();
Run Code Online (Sandbox Code Playgroud)
但是问题在于,不是通过“ userid”创建文档,而是通过以下名称创建文档:
Instance of 'Future<FirebaseUser>'
Run Code Online (Sandbox Code Playgroud)
从字面上看,这是我现在的文档名称,但是我想专门使其成为用户名。
我该怎么办?
uid是FirebaseUser对象的属性。由于auth.currentUser()返回一个future,因此必须等待以获取如下用户对象:
void inputData() async {
final FirebaseUser user = await auth.currentUser();
final uid = user.uid
// here you write the codes to input the data into firestore
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 Google 登录,您将获得此用户信息。
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = new GoogleSignIn();
void initState(){
super.initState();
firebaseAuth.onAuthStateChanged
.firstWhere((user) => user != null)
.then((user) {
String user_Name = user.displayName;
String image_Url = user.photoUrl;
String email_Id = user.email;
String user_Uuid = user.uid; // etc
}
// Give the navigation animations, etc, some time to finish
new Future.delayed(new Duration(seconds: 2))
.then((_) => signInWithGoogle());
}
Future<FirebaseUser> signInWithGoogle() async {
// Attempt to get the currently authenticated user
GoogleSignInAccount currentUser = _googleSignIn.currentUser;
if (currentUser == null) {
// Attempt to sign in without user interaction
currentUser = await _googleSignIn.signInSilently();
}
if (currentUser == null) {
// Force the user to interactively sign in
currentUser = await _googleSignIn.signIn();
}
final GoogleSignInAuthentication googleAuth =
await currentUser.authentication;
// Authenticate with firebase
final FirebaseUser user = await firebaseAuth.signInWithGoogle(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
);
assert(user != null);
assert(!user.isAnonymous);
return user;
}
Run Code Online (Sandbox Code Playgroud)
您需要等待异步操作完成。
final FirebaseUser user = await auth.currentUser();
final userid = user.uid;
Run Code Online (Sandbox Code Playgroud)
或者您可以使用 then 样式语法:
final FirebaseUser user = auth.currentUser().then((FirebaseUser user) {
final userid = user.uid;
// rest of the code| do stuff
});
Run Code Online (Sandbox Code Playgroud)
final FirebaseAuth _auth = FirebaseAuth.instance;
getCurrentUser() async {
final FirebaseUser user = await _auth.currentUser();
final uid = user.uid;
// Similarly we can get email as well
//final uemail = user.email;
print(uid);
//print(uemail);
}
Run Code Online (Sandbox Code Playgroud)
调用函数 getCurrentUser 获取结果。例如,我使用了一个按钮:
RaisedButton(
onPressed: getCurrentUser,
child: Text('Details'),
),
Run Code Online (Sandbox Code Playgroud)
要获取有关用户的 uid、电子邮件和其他信息,请检查用户是否已登录,然后从类中检索这些值User。
User? user = FirebaseAuth.instance.currentUser;
// Check if the user is signed in
if (user != null) {
String uid = user.uid; // <-- User ID
String? email = user.email; // <-- Their email
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6404 次 |
| 最近记录: |