Flutter Navigator.of(context).pop vs Navigator.pop(context)



Navigator.of(context).popNavigator.pop(context)有什么区别?

对我来说,两者似乎都在做同样的工作,实际区别是什么。一个被弃用了吗?

Navigator.push(context, route)vs Navigator.of(context).push(route)

导航器用于管理应用程序的页面(路由)堆栈。当将给定的路线推送到屏幕上(导航器)时,我们需要获得正确的导航器,然后推送。

Navigator.of(context).push(route)拆分.of(context)以获得正确的导航器和.push(route)Navigator.of(context)有可选参数,如果rootNavigator设置为 true,则改为给出最远的导航器状态。

static NavigatorState of(
BuildContext context, {
bool rootNavigator = false,
bool nullOk = false,
})

Navigator.push(context, route)是一种静态方法,可以同时执行这两种操作。它在内部调用Navigator.of(context).push(route)。导航器最紧密地包围了给定的上下文。

static Future<T> push<T extends Object>(BuildContext context, Route<T> route) {
return Navigator.of(context).push(route);
}

pop()类似于push()

当多个导航器嵌套在应用程序中时。showDialog(...)方法创建的对话框路由将推送到根导航器。如果应用程序有多个 Navigator 对象,则可能需要调用Navigator.of(context, rootNavigator: true).pop(result)来关闭对话框,而不仅仅是Navigator.pop(context, result)

两者之间没有区别,源代码证实了这一点。叫

Navigator.pop(context)

实际调用

Navigator.of(context).pop()

源代码:

static bool pop(BuildContext context, [ dynamic result ]) {
return Navigator.of(context).pop(result);
}

有点(不是真的有点)晚了,但我注意到这两者之间的主要区别是Navigator.pop(context)调用Navigator.of(context).pop()当前小部件的BuildContext

基本上,Navigator.of(context).pop()从传递的上下文中获取NavigatorState,并从导航器中弹出最顶层的路由。因此,当您直接使用它时,它会从父级的Navigator(这是您当前所在的路线)中弹出最顶层的路由。当你做Navigator.pop(context)时,你正在做Navigator.of(<current widget's context>).pop()通常做同样的事情,因为当前小部件通常在最上面的路线上。

要查看对象之间的差异,您可以尝试检查它们的哈希代码。例如,使用下面的代码,您可以查看是否使用相同的BuildContext实例调用该函数。

final navigatorState = Navigator.of(context);
print(navigatorState.context.hashCode); // Prints the parent's context's hash code.
print(context.hashCode); // Prints the current widget's context's hash code.

但是,例如,当您在当前上下文上调用showDialog并且您的小部件重建时,当对话框仍在显示时,这可能会变得棘手。在这种情况下,如果您尝试弹出带有Navigator.pop(context)对话框,您可能会遇到异常,例如:

The following assertion was thrown while handling a gesture:
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by
calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

在此用例中,使用Navigator.of(context).pop()会更好。