How to get the current user id from Firebase in Fl

2019-07-24 14:17发布

问题:

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 -

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?

回答1:

uid is a property of FirebaseUser object. Since auth.currentUser() return a future, you have to await in order to get the user object like this:

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


回答2:

You need to wait for the asynchronous operation to complete.

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

or you can use the then style syntax:

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


回答3:

If you are using sign in with Google than you will get this info of user.

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


回答4:

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