【问题标题】:Flutter check is page on top of the screen stack颤振检查是屏幕堆栈顶部的页面
【发布时间】:2020-11-08 05:20:51
【问题描述】:

我有一个页面 A 为每个时间间隔执行一些任务。我只想在页面 A 处于活动状态并显示在屏幕上时执行这些任务。

如果屏幕显示页面 B,则不会执行任务。

我应该如何解决这个问题?

【问题讨论】:

  • 如果您喜欢我的回答,请随意点赞并将其设置为接受的答案。
  • 你有答案吗?

标签: flutter flutter-routes


【解决方案1】:

不检查页面堆栈是相当简单的。因为如果它位于页面堆栈的顶部,则仅当该页面当前处于活动状态时才会出现这种情况,这意味着所有其他页面都将从堆栈中删除(弹出)。如果您使用Navigator.of(context).push.... 调用新页面,为了“暂停”上一页,您可以await 执行该操作。以下示例将使用一个周期性计时器(请记住,您必须将其置于函数范围之外,例如,在状态中)并将其分配给已经存在的 Timer 变量。

Timer t; //a variable in a Stateful widget

@override
void initState() {
  super.initState();

  //it's initialized somewhere and is already working
  t = Timer.periodic(
    Duration(milliseconds: 500),
    (t) => print(
      'CALL YOUR FUNCTION HERE ${t.tick}',
    ),
  );
}

_someMethodInvokingPageB() async {
  // Cancel the timer before the opening the second page
  // no setState((){}) is needed here
  t.cancel();

  // Your calling of Page B. Key is the word AWAIT
  // AWAIT will pause here until you are on the Page B
  var result = await Navigator.of(context).pushNamed('/pageB');

  // reassign a timer to your timer
  // you don't need setState((){}) here
  t = Timer.periodic(
  Duration(milliseconds: 500),
    (t) => print('CALL YOUR FUNCTION HERE ${t.tick}'),
  );
}

这就是你有一个计时器的方式,你有一个方法,你打开Page B,在打开Page B之前取消那个计时器,awaitPage B的打开,在你完成Page B上的东西之后,您将一个新计时器重新分配给您的 Timer t 变量。

附:不要忘记在您的dispose() 方法中调用t.cancel()!

【讨论】:

    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2020-11-08
    • 2021-01-19
    相关资源
    最近更新 更多