简体   繁体   English

调用 Navigator.of(context).pop() 后如何获取父上下文?

[英]How to get the parent context after calling Navigator.of(context).pop()?

How to get the correct context after calling Navigator.of(context).pop() ?调用Navigator.of(context).pop()后如何获取正确的上下文?

Example:例子:

ElevatedButton(
  child: Text('Test'),
  onPressed: () {
    Navigator.of(context).pop();
    showLoadingDialog(context);
  })

The showLoadingDialog is basically a wrap of showDialog call which requires a context . showLoadingDialog基本上是一个需要contextshowDialog调用的包装。 But in my understanding the context is changed for calling Navigator.of(context).pop() .但据我了解,调用Navigator.of(context).pop()的上下文发生了变化。 The reason I need to call pop() is because this ElevatedButton is on a SimpleDialog , and it needs to be closed by calling pop() .我需要调用pop()的原因是因为此ElevatedButton位于SimpleDialog上,需要通过调用pop()将其关闭。

During test, this example gives errors:在测试期间,此示例给出错误:

E/flutter ( 6989): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter ( 6989): At this point the state of the widget's element tree is no longer stable.
E/flutter ( 6989): 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.

After reading some docs and using them in my project, I still can't fully understand context.在阅读了一些文档并在我的项目中使用它们之后,我仍然无法完全理解上下文。 Any help is appreciated, thanks!任何帮助表示赞赏,谢谢!

What you have to remember is that the views are placed in a stack.您必须记住的是视图被放置在堆栈中。 So when you call Navigator.of(context).pop(), it removes your current view and gets you to the previous one.因此,当您调用 Navigator.of(context).pop() 时,它会删除您当前的视图并将您带到前一个视图。 Try wrapping the navigator on a widget and that might solve your issue.尝试将导航器包装在小部件上,这可能会解决您的问题。

I solved it in my own case: Because showDialog needs a builder which makes a new context .我在自己的情况下解决了它:因为showDialog需要一个生成新context的构建器。 Give it a different name for example 'contextOfDialog', change the above codes to给它一个不同的名称,例如“contextOfDialog”,将上面的代码更改为

ElevatedButton(
  child: Text('Test'),
  onPressed: () {
    Navigator.of(contextOfDialog).pop();
    showLoadingDialog(context);
  })

And this will work properly.这将正常工作。 Since the context is the proper one after pop() is called.因为在调用pop()之后context是正确的。

My solution essentially is passing the parent context as parameter.我的解决方案本质上是将父context作为参数传递。 However the question still remains: when you only have the access to the current context , how to get the parent context after pop() ?但是问题仍然存在:当您只能访问当前context时,如何在pop()之后获取父context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM