简体   繁体   English

如何从Flutter中的Firebase获取当前用户id

[英]How to get the current user id from Firebase in Flutter

I am trying this -我正在尝试这个 -

final Future<FirebaseUser> user = auth.currentUser();

but the problem is that instead of making a document by the "userid" it is making a document by the name of -但问题是,它不是通过“userid”制作文档,而是通过名称制作文档 -

Instance of 'Future<FirebaseUser>'

This is literally my documents name right now, but I want to make it the userid specifically.这实际上是我现在的文档名称,但我想专门将其设为用户标识。

What should I do?我应该怎么办?

Update (2020.09.09)更新 (2020.09.09)

After firebase_auth version 0.18.0 firebase_auth 版本 0.18.0 之后

Few breaking updates were made in firebase_auth 0.18.0. firebase_auth 0.18.0 中几乎没有重大更新。 FirebaseUser is now called User, currentUser is a getter, and currentUser is synchronous. FirebaseUser 现在被称为 User,currentUser 是一个 getter,而 currentUser 是同步的。

This makes the code for getting uid like this:这使得获取 uid 的代码如下:

final FirebaseAuth auth = FirebaseAuth.instance;

void inputData() {
    final User user = auth.currentUser;
    final uid = user.uid;
    // here you write the codes to input the data into firestore
  }

Before firebase_auth version 0.18.0在 firebase_auth 版本 0.18.0 之前

uid is a property of FirebaseUser object. uid 是 FirebaseUser 对象的一个​​属性。 Since auth.currentUser() return a future, you have to await in order to get the user object like this:由于 auth.currentUser() 返回未来,您必须等待才能像这样获取用户对象:

final FirebaseAuth auth = FirebaseAuth.instance;

void inputData() async {
    final FirebaseUser user = await auth.currentUser();
    final uid = user.uid;
    // here you write the codes to input the data into firestore
  }

You need to wait for the asynchronous operation to complete.您需要等待异步操作完成。

final FirebaseUser user = await auth.currentUser();
final userid = user.uid;

or you can use the then style syntax:或者您可以使用 then 样式语法:

final FirebaseUser user = auth.currentUser().then((FirebaseUser user) {
  final userid = user.uid;
  // rest of the code|  do stuff
});

If you are using sign in with Google than you will get this info of user.如果您使用 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;
}
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);
  }

Call the function getCurrentUser to get the result.调用函数 getCurrentUser 以获取结果。 For example, I used a button:例如,我使用了一个按钮:

RaisedButton(
              onPressed: getCurrentUser,
              child: Text('Details'),
            ),

This is another way of solving it:这是另一种解决方法:

Future<String> inputData() async {
    final FirebaseUser user = await FirebaseAuth.instance.currentUser();
    final String uid = user.uid.toString();
  return uid;
  }

it returns the uid as a String它将uid作为字符串返回

you can also try this.你也可以试试这个。

     currentUser() {
         final User user = _firebaseAuth.currentUser;
         final uid = user.uid.toString();
         return uid;
      }

now just call currentUser() in your code and it will return uid of the currently logged-in user.现在只需在您的代码中调用currentUser() ,它将返回当前登录用户的 uid。

    uid=FirebaseAuthService().currentUser();

Doing it normaly will always return照常做总会回来

Instance of 'Future<FirebaseUser>'

Try using .then as follows尝试使用 .then 如下

First Create function in your authservice class首先在您的 authservice 类中创建函数

Future<String> getCurrentUID() async{
    final FirebaseUser user = await _auth.currentUser();
    final String uid = user.uid;
    return uid;
  }

Then call this function where you wnat this ID as Following然后调用这个函数,你把这个 ID 设为以下

Widget build(BuildContext context) {
    void getid(String foo) {
      userID = foo;
    }

    AuthService().getCurrentUID().then((value) => getid(value));

    return Scaffold(
      ...
    );
}

This is most convenient method to get the ID You can also get email and mobile no.这是获取 ID 的最便捷方法您还可以获取电子邮件和手机号码。 like this.像这样。

You may add this into the global state before your flutter widget.您可以在 flutter 小部件之前将其添加到全局状态中。

final FirebaseAuth auth = FirebaseAuth.instance;
final User user = auth.currentUser;
final myUid = user.uid;

it will make myUid available for this situation.它将使myUid可用于这种情况。

This is a very comprehensive resource to solve all issues related to registration and login in Flutter with updated Firebase code.这是一个非常全面的资源,可以使用更新的 Firebase 代码解决与 Flutter 中注册和登录相关的所有问题。 https://kickertech.com/login-and-register-easily-with-flutter-using-firebase/ https://kickertech.com/login-and-register-easily-with-flutter-using-firebase/

Update (Null safe)更新(空安全)

To get uid, email, and other information about the user, check if the user is signed in and then retrieve these values from the User class.要获取有关用户的 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
}

Update 2023 with null safety使用null safety更新 2023

Current User Id:当前用户 ID:

  FirebaseAuth.instance.currentUser?.uid

Current User Name:当前用户名:

  FirebaseAuth.instance.currentUser?.displayName

Current User Email:当前用户 Email:

  FirebaseAuth.instance.currentUser?.email

Current User Phone Number:当前用户电话号码:

  FirebaseAuth.instance.currentUser?.phoneNumber

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

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