WidgetsBindingRaiiExt extension

Extension that provides a more direct way to add lifecycle-managed observers to the WidgetsBinding instance.

Example:

// Basic app lifecycle observer
class AppLifecycleObserver with WidgetsBindingObserver {
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print('App resumed');
        break;
      case AppLifecycleState.inactive:
        print('App inactive');
        break;
      case AppLifecycleState.paused:
        print('App paused');
        break;
      case AppLifecycleState.detached:
        print('App detached');
        break;
    }
  }
}

// Attach the observer
final lifecycleObserver = AppLifecycleObserver();
WidgetsBinding.instance.addObserverWithLifeycle(
  lifecycleAware,
  lifecycleObserver,
  debugLabel: 'AppLifecycle',
);

// System settings observer
class SystemSettingsObserver with WidgetsBindingObserver {
  @override
  void didChangePlatformBrightness() {
    print('Brightness changed');
  }

  @override
  void didChangeLocales(List<Locale>? locales) {
    print('Locales changed');
  }
}

// Attach the system observer
final settingsObserver = SystemSettingsObserver();
WidgetsBinding.instance.addObserverWithLifeycle(
  lifecycleAware,
  settingsObserver,
);
on

Methods

addObserverWithLifeycle(RaiiLifecycleAware lifecycleAware, WidgetsBindingObserver observer, {String? debugLabel}) → void

Available on WidgetsBinding, provided by the WidgetsBindingRaiiExt extension

Adds a listener that will be automatically removed when the lifecycleAware is disposed.