【问题标题】:initState() method of first activity is not initializing after taking popback stack from the aother activity从另一个活动获取 popbackstack 后,第一个活动的 initState() 方法未初始化
【发布时间】:2021-06-24 07:47:12
【问题描述】:

我正在开发使用 3 个屏幕的颤振应用程序。

MainActivityActivityClass1 开放,ActivityClass1 将打开 ActivityClass2。现在,当我从 ActivityClass2 中获取 Navigator.pop(context), 时,它将显示堆栈中的 ActivityClass1。但是这次我需要在ActivityClass1 中取initState(),因为我需要刷新ActivityClass1 上的一些数据。

有什么方法可以调用ActivityClass1initState() 来维护MainActivity -> ActivityClass1 的堆栈吗? 我也尝试过Navigator.of(context).pushAndRemoveUntil(,而不是在ActivityClass2 上使用Navigator.pop(context),,但这会清除我的堆栈。

【问题讨论】:

    标签: flutter flutter-layout flutter-state


    【解决方案1】:

    Navigator.push 在解析传递给它的MaterialPageRoute 时返回Future。您可以等待 Future 以了解其他视图何时弹出。

    例子,

    Navigator.of(context).push(MaterialPageRoute(
      builder: 
        (context) => NewView(),
      ),
    ).then((_) {
      // Call setState() here or handle this appropriately
    });
    

    所以现在当我回到我的 Activity Class1 时,这个方法将有助于在返回屏幕时采取任何行动,只需使用 Navigator.pop(context),

    【讨论】:

      【解决方案2】:

      不要使用Navigator.of(context).pop,而是使用:

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => SecondRoute()),
      );
      

      【讨论】:

      • 如果我将再次使用Navigator.push 调用,那么这个屏幕也将被添加到我的堆栈中,所以现在如果我按下返回,这将显示为 Screen1 -> Screen2 -> Screen1 - > 主要活动。这是错误的流程。从 screen2 按下后,我需要在我的堆栈中作为 screen1 -> MainActivity 工作的东西。
      • 使用 pushReplacement
      【解决方案3】:

      如果你想重新开始屏幕的初始状态,你可以在想要返回时使用 pushReplacement 而不是 Pop()。 它对我有用:

      使用 pushReplacement 转到 ActivityClass2 并返回到 ActivityClass1

      ActivityClass2 -> ActivityClass1

      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => ActivityClass1(),
        ),
      );
      

      【讨论】:

      • 我尝试了相同的解决方案,但这可以创建一个类似于 MainActivity() -> Screen1 -> Screen1 的堆栈。所以现在当我从 screen1 按下返回时,它会再次弹出到 Screen1。
      猜你喜欢
      • 1970-01-01
      • 2011-10-20
      • 2018-11-17
      • 2015-02-16
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      相关资源
      最近更新 更多