Created
August 20, 2023 10:20
-
-
Save StanislawNagorski/bb48b7a6a7f0ec042b1559f5ab53d0fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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