Ashwani Kumar
Ashwani Kumar

Reputation: 234

How convert FirebaseUser to string in flutter?

Here is my code of a stateful class:

String id = FirebaseAuth.instance.currentUser().toString();

my function :

readLocal() async {
  prefs = await SharedPreferences.getInstance();
  id = prefs.getString('id') ?? '';
  if (id.hashCode <= peerId.hashCode) {
    groupChatId = '$id-$peerId';
  } else {
    groupChatId = '$peerId-$id';
  }
  setState(() {});
}

It works fine in String id.

I want the ID to be the same as the current user UID.

Upvotes: 0

Views: 1605

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600110

Calling FirebaseAuth.instance.currentUser() return a FirebaseUser, which is an object with all user data. If you only want the UID of the user:

FirebaseUser user = await FirebaseAuth.instance.currentUser();
String uid = user.uid;

Update: I just ran this and it prints the UID for me:

void _getUser() async {
  FirebaseUser user = await FirebaseAuth.instance.currentUser();
  print(user.uid);
}

Which printed:

flutter: P07IXLCrwEahYlDhzO1Iv0SKDat2

Things to notice:

  • In order to be able to use await in the code, the method must be marked as async.

Upvotes: 1

Related Questions