didChangeAppLifecycleState method
- AppLifecycleState state
override
Called when the system puts the app in the background or returns the app to the foreground.
An example of implementing this method is provided in the class-level documentation for the WidgetsBindingObserver class.
This method exposes notifications from SystemChannels.lifecycle.
See also:
- AppLifecycleListener, an alternative API for responding to application lifecycle changes.
Implementation
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
assert(_debugAssertNotDisposed());
final AppLifecycleState? previousState = _lifecycleState;
if (state == previousState) {
// Transitioning to the same state twice doesn't produce any
// notifications (but also won't actually occur).
return;
}
_lifecycleState = state;
switch (state) {
case AppLifecycleState.resumed:
assert(previousState == null || previousState == AppLifecycleState.inactive || previousState == AppLifecycleState.detached, 'Invalid state transition from $previousState to $state');
onResume?.call();
case AppLifecycleState.inactive:
assert(previousState == null || previousState == AppLifecycleState.hidden || previousState == AppLifecycleState.resumed, 'Invalid state transition from $previousState to $state');
if (previousState == AppLifecycleState.hidden) {
onShow?.call();
} else if (previousState == null || previousState == AppLifecycleState.resumed) {
onInactive?.call();
}
case AppLifecycleState.hidden:
assert(previousState == null || previousState == AppLifecycleState.paused || previousState == AppLifecycleState.inactive, 'Invalid state transition from $previousState to $state');
if (previousState == AppLifecycleState.paused) {
onRestart?.call();
} else if (previousState == null || previousState == AppLifecycleState.inactive) {
onHide?.call();
}
case AppLifecycleState.paused:
assert(previousState == null || previousState == AppLifecycleState.hidden, 'Invalid state transition from $previousState to $state');
if (previousState == null || previousState == AppLifecycleState.hidden) {
onPause?.call();
}
case AppLifecycleState.detached:
assert(previousState == null || previousState == AppLifecycleState.paused, 'Invalid state transition from $previousState to $state');
onDetach?.call();
}
// At this point, it can't be null anymore.
onStateChange?.call(_lifecycleState!);
}