Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save StanislawNagorski/bb48b7a6a7f0ec042b1559f5ab53d0fd to your computer and use it in GitHub Desktop.
Save StanislawNagorski/bb48b7a6a7f0ec042b1559f5ab53d0fd to your computer and use it in GitHub Desktop.
import 'dart:developer';
import 'package:flutter/widgets.dart';
class AppLifeCycleWidgetWrapper extends StatefulWidget {
const AppLifeCycleWidgetWrapper({
required this.child,
this.onMoveToForeground,
this.onMoveToBackground,
this.onAppPaused,
this.onAppDetached,
super.key,
});
final Widget child;
final VoidCallback? onMoveToForeground;
final VoidCallback? onMoveToBackground;
final VoidCallback? onAppPaused;
final VoidCallback? onAppDetached;
@override
State<AppLifeCycleWidgetWrapper> createState() => _AppLifeCycleWidgetWrapperState();
}
class _AppLifeCycleWidgetWrapperState extends State<AppLifeCycleWidgetWrapper> with WidgetsBindingObserver {
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
widget.onMoveToForeground?.call();
log('App move to FOREGROUND');
break;
case AppLifecycleState.inactive:
widget.onMoveToBackground?.call();
log('App move to BACKGROUND');
break;
case AppLifecycleState.paused:
widget.onAppPaused?.call();
log('App PAUSED');
break;
case AppLifecycleState.detached:
widget.onAppDetached?.call();
log('App DETACHED');
break;
}
}
@override
Widget build(BuildContext context) => widget.child;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment