我试图很好地理解Flutter Lifecycle,我不确定像PUSH这样的事件发生两次是正常的。我正在搜索仅在显示视图时发生一次的事件。例如:ViewA显示eventImSearchingOn只发生一次。 ViewA打开ViewB,ViewA停用。 ViewB返回ViewA,eventImSearchingOn只发生一次。
我尝试过的代码日志:
InitState SplashScreenUI
ChangeDependencies SplashScreenUI
PUSH SplashScreenUI
InitState SplashScreenUI
ChangeDependencies SplashScreenUI
PUSH SplashScreenUI
主类
@override
Widget build(BuildContext context) {
return StoreProvider<AppState>(
store: widget.store,
child: MaterialApp(
...
....
initialRoute: '/SplashScreen',
home: SplashScreenUI(),
navigatorKey: Keys.navKey,
navigatorObservers: [Keys.routeObserver],
routes: <String, WidgetBuilder>{
'/Home': (BuildContext context) => HomePageUI(),
'/Login': (BuildContext context) => LoginPageUI(),
'/Routine': (BuildContext context) => RoutineUI(),
'/Notifications': (BuildContext context) => NotificationsUI(),
'/Chat': (BuildContext context) => ChatUI(),
'/Profile': (BuildContext context) => ProfileUI(),
'/ProfileForm': (BuildContext context) => ProfileFormUI(),
'/Interview': (BuildContext context) => InterviewUI(),
'/BodyCheck': (BuildContext context) => BodyCheckUI(),
'/SplashScreen': (BuildContext context) => SplashScreenUI(),
SplashScreen类
class _SplashScreenUIState extends State<SplashScreenUI> with RouteAware{
_SplashScreenUIState();
@override
void initState() {
print("InitState SplashScreenUI");
super.initState();
store.dispatch(CheckLogIn());
}
@override
void didChangeDependencies() {
print("ChangeDependencies SplashScreenUI");
super.didChangeDependencies();
Keys.routeObserver.subscribe(this, ModalRoute.of(context));
}
@override
void deactivate() {
print("Deactivate SplashScreenUI");
super.deactivate();
}
@override
void dispose() {
print("Dispose SplashScreenUI");
Keys.routeObserver.unsubscribe(this);
super.dispose();
}
@override
void didPush() {
print("PUSH SplashScreenUI");
}
@override
void didPopNext() {
print("POP SplashScreenUI");
}
对不起,问题在于:
initialRoute: '/SplashScreen',
home: SplashScreenUI(),
这个双重声明导致SplashScreen被调用两次。改变这个,解决问题。
home: SplashScreenUI(),