简体   繁体   中英

How to get user id from Firebase Auth in Flutter?

I want to save user-related data in Firestore by assigning user id to a document as a field.

How to get user id from Firebase Auth?

Or is there a better way to store user data in Firestore?

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 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...');
        }
      },
    ),
  );
}

Current User Id:

  FirebaseAuth.instance.currentUser?.uid

To store user details in the uid :

Use set() method:

final user = <String, String>{
  "name": "Mohan Roy",
  "state": "CA",
  "country": "USA"
};

Firestore.instance
    .collection("users")
    .doc(FirebaseAuth.instance.currentUser!.uid)
    .set(user)
    .onError((e, _) => print("Error writing document: $e"));

Extra:

Current User Name:

  FirebaseAuth.instance.currentUser?.displayName

Current User Email:

  FirebaseAuth.instance.currentUser?.email

Current User Phone Number:

  FirebaseAuth.instance.currentUser?.phoneNumber

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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