app_lifecycle_widget.dart 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import 'package:flutter/cupertino.dart';
  2. /// App前台、后台切换时回调
  3. /// [isForeground] 是否前台
  4. typedef OnAppLifecycleChangeCallback = void Function(bool isForeground);
  5. /// 监听App前后台的组件
  6. class AppLifecycleWidget extends StatefulWidget {
  7. /// 子组件
  8. final Widget child;
  9. final OnAppLifecycleChangeCallback? onAppLifecycleCallback;
  10. const AppLifecycleWidget({
  11. super.key,
  12. required this.child,
  13. this.onAppLifecycleCallback,
  14. });
  15. @override
  16. State<StatefulWidget> createState() {
  17. return _AppLifecycleWidgetState();
  18. }
  19. }
  20. class _AppLifecycleWidgetState extends State<AppLifecycleWidget>
  21. with WidgetsBindingObserver {
  22. @override
  23. void initState() {
  24. super.initState();
  25. // 添加App生命周期监听
  26. WidgetsBinding.instance.addObserver(this);
  27. }
  28. @override
  29. void dispose() {
  30. // 移除App生命周期监听
  31. WidgetsBinding.instance.removeObserver(this);
  32. super.dispose();
  33. }
  34. @override
  35. void didChangeAppLifecycleState(AppLifecycleState state) {
  36. super.didChangeAppLifecycleState(state);
  37. // 切换到前台
  38. if (state == AppLifecycleState.resumed) {
  39. if (widget.onAppLifecycleCallback != null) {
  40. widget.onAppLifecycleCallback!(true);
  41. }
  42. } else if (state == AppLifecycleState.paused) {
  43. // 切换到后台
  44. if (widget.onAppLifecycleCallback != null) {
  45. widget.onAppLifecycleCallback!(false);
  46. }
  47. }
  48. }
  49. @override
  50. Widget build(BuildContext context) {
  51. return widget.child;
  52. }
  53. }