Flutter: Listen to auth events (original) (raw)

Receive a notification every time an auth event happens.

Examples

Listen to auth changes

final authSubscription = supabase.auth.onAuthStateChange.listen((data) {
  final AuthChangeEvent event = data.event;
  final Session? session = data.session;

  print('event: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>e</mi><mi>v</mi><mi>e</mi><mi>n</mi><mi>t</mi><mo separator="true">,</mo><mi>s</mi><mi>e</mi><mi>s</mi><mi>s</mi><mi>i</mi><mi>o</mi><mi>n</mi><mo>:</mo></mrow><annotation encoding="application/x-tex">event, session: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.854em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">e</span><span class="mord mathnormal">n</span><span class="mord mathnormal">t</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">sess</span><span class="mord mathnormal">i</span><span class="mord mathnormal">o</span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>session');

  switch (event) {
    case AuthChangeEvent.initialSession:
    // handle initial session
    case AuthChangeEvent.signedIn:
    // handle signed in
    case AuthChangeEvent.signedOut:
    // handle signed out
    case AuthChangeEvent.passwordRecovery:
    // handle password recovery
    case AuthChangeEvent.tokenRefreshed:
    // handle token refreshed
    case AuthChangeEvent.userUpdated:
    // handle user updated
    case AuthChangeEvent.userDeleted:
    // handle user deleted
    case AuthChangeEvent.mfaChallengeVerified:
    // handle mfa challenge verified
  }
});

Listen to a specific event

final authSubscription = supabase.auth.onAuthStateChange.listen((data) {
  final AuthChangeEvent event = data.event;
  if (event == AuthChangeEvent.signedIn) {
    // handle signIn
  }
});

Unsubscribe from auth subscription

final authSubscription = supabase.auth.onAuthStateChange.listen((data) {});

authSubscription.cancel();