在Flutter中PUSH事件发生两次是正常的吗?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Flutter中PUSH事件发生两次是正常的吗?相关的知识,希望对你有一定的参考价值。

我试图很好地理解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(),

以上是关于在Flutter中PUSH事件发生两次是正常的吗?的主要内容,如果未能解决你的问题,请参考以下文章

vscode保存代码自动编译两次是怎么回事

onclick 事件在 iPhone 混合应用程序中发生了两次

Redis Server 一天宕机两次是啥原因?

Spring MVC Web 应用程序:应用程序上下文启动两次

TSINGSEE青犀视频启动行人检测功能程序出现启动两次是什么原因?

Keydown事件发生两次