Search code examples
flutterauthenticationsupabase

Can't listen for signUp and EmailRegistration events on Supabase in Flutter


I'm trying to catch a user register and email confirmation event. In the register page, I have supabase.auth.onAuthStateChange event listener that redirects them to another screen saying to click on the link on the email when the user signUp.

In this confirmation screen, I have another event listener that tracks the confirmation process. When I happens, it redirects them to the main page.

The docs says:

If Confirm email is enabled, a user is returned but session is null.

If Confirm email is disabled, both a user and a session are returned.

So, here's the event listener on the register page:

late final StreamSubscription<AuthState> _authSubscription;
  @override
  void initState() {
    super.initState();
    _authSubscription = supabase.auth.onAuthStateChange.listen((event) {
      final session = event.session;
      print('printing session on RegisterPage: $session\n\n');
      if (session?.user != null) {
        Navigator.of(context).pushReplacementNamed('/confirm_email');
      }
    });
  }

The listener on the confirmation email page:

late final StreamSubscription<AuthState> _authSubscription;
  @override
  void initState() {
    super.initState();
    _authSubscription = supabase.auth.onAuthStateChange.listen((event) {
      final session = event.session;
      print('printing session on ConfirmEmailPage: $session\n\n');
      if (session?.user != null) {
        Navigator.of(context).pushReplacementNamed('/home');
      }
    });
  }

My email confirmation is on. I didn't see any print on the degub console either. Can you guys help me stop the issue? Thank you.


Solution

  • If Confirm email is enabled, a user is returned but session is null.

    If Confirm email is disabled, both a user and a session are returned.

    The above is talking about the return value of .signUp() call, and not the behavior of the onAuthStateChange event callback.

    For the register page, if you just want to show a confirmation page to the user after the signUp, no need to do anything with the onAuthStateChange callback, and just navigate the user after the .signUp() call like this:

    await supabase.auth.signUp(
      // the user credentials here
    );
    
    Navigator.of(context).pushReplacementNamed('/confirm_email');
    

    You are correct at relying on the onAuthStateChange on the confirmation page, so keep that one.