flutterfirebasefirebase-authenticationstream-builder

In Flutter, how to properly handle authentication?


I am using firebase for authentication. I listen in a StreamBuilder for authStateChanges():

I have tried using Navigator.pop, on logout, but this feels like a hack. What if I have multiple pages on the stack?


Solution

  • You are handling the auth correctly.

    The issue could be in your navigation there are three possibilities:

    I: If you are using named routes you can use:

    Navigator.popUntil(context, (route) => route.settings.name == '/home');
    

    II: If you are using not using named routes: Check out this answer: Flutter Navigation pop to index 1

    Navigator.of(context).popUntil((route) => route.isFirst);
    

    /!\ For the two first methods, call these function when detecting a logout action.

    III: Use a package to help you manage the Navigation