Flutter

Widgets

AuthyraScope, AuthStateBuilder and the splash screen.

AuthyraScope

Put it above your app. It makes the instance available to descendants and refreshes the active session when the app returns to the foreground if it is due, since timers do not run while a mobile app is suspended.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final authyra = await Authyra.initialize(
    storage: SecureAuthStorage(),
    providers: [apiProvider],
  );
  runApp(AuthyraScope(authyra: authyra, child: const App()));
}
final authyra = AuthyraScope.of(context);      // Throws if there is no scope.
final maybe = AuthyraScope.maybeOf(context);    // Null if there is none.

of does not rebuild your widget when the state changes. Use AuthStateBuilder for that.

AuthStateBuilder

Rebuilds when the auth state changes. Token refreshes do not trigger a rebuild.

AuthStateBuilder(
  builder: (context, state) => switch (state) {
    AuthUnknown() => const SplashScreen(),
    AuthSignedIn(:final user) => HomeScreen(user: user),
    AuthSignedOut() => const SignInScreen(),
  },
)

It uses the enclosing AuthyraScope, or the instance you pass with authyra:.

The splash screen

AuthUnknown lasts while saved sessions are read from the keystore, usually a few dozen milliseconds. Render a splash, not the sign-in screen: otherwise signed-in users see the sign-in screen flash at every launch.

Since Authyra.initialize already awaits the restore, you can also keep the native splash until it returns and never render AuthUnknown at all.

Reacting to events

Widgets render state; side effects (a snackbar when a session is revoked, analytics) belong in an event listener:

class _HomeState extends State<Home> {
  StreamSubscription<AuthEvent>? _events;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _events ??= AuthyraScope.of(context).events.listen((event) {
      if (event case SessionEndedEvent(reason: SessionEndReason.revoked)) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Your session ended. Please sign in again.')),
        );
      }
    });
  }

  @override
  void dispose() {
    _events?.cancel();
    super.dispose();
  }

  // ...
}
Copyright © 2026