import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:router/observer/getx_router_observer.dart'; /* * StatefulWidget 的生命周期实现基于原生实现 */ mixin StateLifecycle on State implements RouteAware, WidgetsBindingObserver, IStateLifecycle { @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void didChangeDependencies() { super.didChangeDependencies(); final route = ModalRoute.of(context); if (route != null && route is PageRoute) { routeObserver.subscribe(this, route); } } @override void dispose() { routeObserver.unsubscribe(this); WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didPop() { onStop(); } @override void didPopNext() { onResume(); } @override void didPush() { onStart(); } @override void didPushNext() { onPause(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { onResume(); } else if (state == AppLifecycleState.paused) { onPause(); } } // =========================== 默认空实现 =========================== @override void didChangeAccessibilityFeatures() {} @override void didChangeLocales(List? locales) {} @override void didChangeMetrics() {} @override void didChangePlatformBrightness() {} @override void didChangeTextScaleFactor() {} @override void didHaveMemoryPressure() {} @override Future didPopRoute() { return Future.value(false); } @override Future didPushRoute(String route) { return Future.value(false); } @override Future didPushRouteInformation(RouteInformation routeInformation) { return didPushRoute(routeInformation.location!); } @override Future didRequestAppExit() async { return AppExitResponse.exit; } @override void onStart() {} @override void onStop() {} @override void onResume() {} @override void onPause() {} } // 自定义生命周期回调接口 abstract class IStateLifecycle { void onStart(); //启动页面 void onStop(); //结束页面 void onResume(); //重新可见 void onPause(); //被覆盖隐藏 }