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


Solution 1: Frank van Puffelen

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.


Solution 2: LoL

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.