如何以及在何处调用 Flutter 中的 Dispose

How and Where to Call Dispose in Flutter

我正在阅读有关如何在 flutter 上使用 dispose 的信息,但我无法弄明白。如果我在 Navigator.pushReplacementNamed 之后调用下面的 pagedispose 函数,我总是会收到错误消息。如果我从另一个 class 页面调用这个函数,我会得到它不存在等错误

感谢您指导如何在转换到另一个 Flutter 页面时清除页面上的所有 运行 功能等。

@override
void pagedispose(){   
    vtimer.cancel();   
    vcontroller.dispose();   
    super.dispose();   
 }

提前致谢。

根据 documentation

处理方法

Called when this object is removed from the tree permanently.

对于一个页面,当页面从导航栈中移除时调用dispose方法。 Here 很好地解释了 Navigation
当您的小部件(页面)扩展 StatefulWidget 时,这不是强制性的,但您可以根据需要覆盖 dispose 方法来执行其他指令。当从导航树中删除页面时,将自动调用该方法。重写方法如下

@override
void dispose() {
  // your desired instructions here

  super.dispose(); // This will free the memory space allocated to the page
}

尽管如此,方法 void pagedispose() 不能被覆盖,因为它不是 StatefulWidget

的已知方法