Flutter Firebase user authentication management across the application

Viewed 567

I have implemented user authentications successfully, everything is working fine, I just want to manage currentUser in an efficient way.

I want to login once and want to access the currentUser in app at any moment.

FirebaseAuth.instance.currentUser()

is a Future<FirebaseUser>, I want to get instantly, I am unable to figure it out how to manage this, I think no need to add code for this, I am just seeking for an idea.

2 Answers

As Sebastian stated, you should look into the Provider or any other state management tool/pattern, but for the example I am going to use you will need the Provider package.

Firebase Auth has an onAuthStateChanged stream that emits the current FirebaseUser if user is signed in or null if not signed in. so what you can do is wrap your MaterialApp with a StreamProvider and in any screen of your app you can access your user info

Example:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return StreamProvider<FirebaseUser>(   //From the Provider package
      stream: FirebaseAuth.instance.onAuthStateChanged,
      child: MaterialApp(
        home: MyScreen(),
      ),
    );
  }
}


class MyScreen extends StatelessWidget {
  Widget build(BuildContext context) {
    FirebaseUser fbUser = Provider.of<FirebaseUser>(context); // this is how you can access the user from anywhere in the app
    return Scaffold(body: Container(child: Text(fbUser.uid ?? "No user"),),);
  }
}

Its worth noting that onAuthStateChanged is stream so if a logout or a login event occurs it immediately emits data according to that event.

Related