0

Currently I am getting currentUser on each flutter screen as follows:

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

Is there a way to just do this once and save data in some form of global variable which can be accessed on all screens. In django we have session object. Is there a equivalent in flutter. Not sure if getting currentuser on each screen is a flutter way of doing things. If so do I create an async func and call it on each screen. I do same thing with FirebaseStorage and Firestore.

thanks

Aseem
  • 5,848
  • 7
  • 45
  • 69

2 Answers2

1

The user's authentication state can change without you making any API calls, for example when the ID token gets refreshed every hour, or when the developer disables an account in the Firebase console.

For this reason, you should almost always treat the user object as transient, and re-retrieve it on each screen.

If the user is still valid, the call is actually pure client-side, and returns immediately (but still asynchronously). In most native Firebase SDK you'd call a synchronous method like FirebaseAuth.getInstance().getCurrentUser() (Android) in some cases, but the authors of the Flutter bindings decided against that, probably because of convenience of Dart's await keyword.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Do you use the same async func that you call on each screen, or do you write a new func (same functionality ) on each screen – Aseem Dec 19 '19 at 01:02
  • Yeah, pretty much. Anything that needs the use state is in an async handler. Which is correct, since the state can change even between statements (although it typicaly wont). – Frank van Puffelen Dec 19 '19 at 01:05
0

Frank's answer is correct.

I think the rationale question is that it is async call and every screen is going to be fed with FutureBuilder making me extremely uncomfortable.

So here is one way how you could avoid it. Some ugly code:

static FirebaseUser currentUser = null;
FirebaseAuth.instance.onAuthStateChanged.listen((FirebaseUser user) => currentUser = user);

Remember to check null, as the user may logout by himself or being kicked externally without.

LoL
  • 162
  • 1
  • 6