Skip to main content

useAppLifecycleState

Observes the app's AppLifecycleState and rebuilds when it changes. It returns the current state and optionally fires a callback on each transition, without a manual WidgetsBindingObserver.

class VideoPlayerControls extends HookWidget {
const VideoPlayerControls({super.key});


Widget build(BuildContext context) {
// The callbacks fire on transitions; the return value is the current state.
final lifecycleState = useAppLifecycleState(
onPaused: () {/* pause playback */},
onResumed: () {/* resume playback */},
);

return Text('App is $lifecycleState'); // <- Rebuilds whenever the state changes
}
}

Signature

AppLifecycleState useAppLifecycleState({
void Function()? onPaused,
void Function()? onResumed,
void Function()? onHidden,
void Function()? onInactive,
});

Returns the current AppLifecycleState, seeded from WidgetsBinding.instance.lifecycleState on the first build and updated on every transition. Each optional callback fires when the app enters the matching state. The callbacks are wrapped internally, so passing a fresh closure on each build is fine - it does not re-register the observer.

Use cases

  • Pausing and resuming work tied to foreground presence: stop a video, a camera preview, or a location stream on onPaused, restart it on onResumed.
  • Refreshing stale data when the user returns to the app (onResumed).
  • Driving UI off the current state by reading the return value, e.g. dimming a screen while inactive.

Caveats

  • The callbacks are side effects fired during the observer's notification, not values you read. Use them for actions (pause, save, refresh); use the return value when the UI itself depends on the lifecycle state.
  • Heavy work in onPaused runs while the app is being backgrounded, where the OS may grant little time. Keep it short - flush what matters, defer the rest.
  • The hook reports app-wide lifecycle, not per-route visibility. To react to a single route scrolling off-screen, use a route-aware mechanism instead.

See also

  • useEffect - the effect primitive this hook builds on to register its observer
  • useState - how the current state is stored and triggers rebuilds