sharath
sharath

Reputation: 3626

What is the cleanest way to access a logged in Firebase user across your Flutter app?

I am using firebase in my flutter app and accessing the logged in user would be done something like this -

  Future<FirebaseUser> getLoggedInUser() async {
    return await FirebaseAuth.instance.currentUser();
  }

I use BLOC and was thinking of adding this to my AuthenticationBloc class. Since this BLOC is injected early, I should be able to access this from anywhere in the app -

AuthenticationBloc authBloc = BlocProvider.of<AuthenticationBloc>(context);
FirebaseUser user = await authBloc.getLoggedInUser()

But this leads to a few problems like accessing this in a StreamBuilder becomes an issue because of the need of using await which means I would need to make the StreamBuilder async (not sure how).

What would be the best/cleanest way of accessing the user object FirebaseUser user from anywhere in the app ?

Thanks !

Edit 1 :

So one way to do this would be to use a stateful widget every time I want the current user

class _MyWidgetState extends State<MyWidget> {
  FirebaseUser user;

  @override
  void initState() {
    super.initState();
    _updateCurrentUser();
  }

  void _updateCurrentUser() async {
    FirebaseUser currUser = await Firebase.instance.currentUser();
    setState(() {
      user = currUser;
    });
  }

But using a stateful widget every time I want the currUser seems weird. Is there a better way out ?

Upvotes: 1

Views: 170

Answers (1)

Khadga shrestha
Khadga shrestha

Reputation: 1180

You can access the user by using stream such as

StreamBuilder(
  stream:FirebaseAuth.instance.onAuthStateChanged,
  builder:(context,snapshot){
     if (snapshot.connectionState == ConnectionState.active) {
        final user = snapshot.data;
         return Text("User Id:${user.uid}");
        }else{
         return Center(
            child:CircularProgressIndicator(),
         );
      }
  }

);

Upvotes: 1

Related Questions