mixin_state_lifecycle.dart 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import 'dart:ui';
  2. import 'package:flutter/material.dart';
  3. import 'package:router/observer/getx_router_observer.dart';
  4. /*
  5. * StatefulWidget 的生命周期实现基于原生实现
  6. */
  7. mixin StateLifecycle<T extends StatefulWidget> on State<T> implements RouteAware, WidgetsBindingObserver, IStateLifecycle {
  8. @override
  9. void initState() {
  10. super.initState();
  11. WidgetsBinding.instance.addObserver(this);
  12. }
  13. @override
  14. void didChangeDependencies() {
  15. super.didChangeDependencies();
  16. final route = ModalRoute.of(context);
  17. if (route != null && route is PageRoute) {
  18. routeObserver.subscribe(this, route);
  19. }
  20. }
  21. @override
  22. void dispose() {
  23. routeObserver.unsubscribe(this);
  24. WidgetsBinding.instance.removeObserver(this);
  25. super.dispose();
  26. }
  27. @override
  28. void didPop() {
  29. onStop();
  30. }
  31. @override
  32. void didPopNext() {
  33. onResume();
  34. }
  35. @override
  36. void didPush() {
  37. onStart();
  38. }
  39. @override
  40. void didPushNext() {
  41. onPause();
  42. }
  43. @override
  44. void didChangeAppLifecycleState(AppLifecycleState state) {
  45. if (state == AppLifecycleState.resumed) {
  46. onResume();
  47. } else if (state == AppLifecycleState.paused) {
  48. onPause();
  49. }
  50. }
  51. // =========================== 默认空实现 ===========================
  52. @override
  53. void didChangeAccessibilityFeatures() {}
  54. @override
  55. void didChangeLocales(List<Locale>? locales) {}
  56. @override
  57. void didChangeMetrics() {}
  58. @override
  59. void didChangePlatformBrightness() {}
  60. @override
  61. void didChangeTextScaleFactor() {}
  62. @override
  63. void didHaveMemoryPressure() {}
  64. @override
  65. Future<bool> didPopRoute() {
  66. return Future<bool>.value(false);
  67. }
  68. @override
  69. Future<bool> didPushRoute(String route) {
  70. return Future<bool>.value(false);
  71. }
  72. @override
  73. Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
  74. return didPushRoute(routeInformation.location!);
  75. }
  76. @override
  77. Future<AppExitResponse> didRequestAppExit() async {
  78. return AppExitResponse.exit;
  79. }
  80. @override
  81. void onStart() {}
  82. @override
  83. void onStop() {}
  84. @override
  85. void onResume() {}
  86. @override
  87. void onPause() {}
  88. }
  89. // 自定义生命周期回调接口
  90. abstract class IStateLifecycle {
  91. void onStart(); //启动页面
  92. void onStop(); //结束页面
  93. void onResume(); //重新可见
  94. void onPause(); //被覆盖隐藏
  95. }