如何解决当零食栏显示在屏幕上并且同时按下后退按钮时,它会在控制台中以 flutter / dart 的形式抛出错误
当snackbar显示在屏幕上并且同时按下后退按钮时,它会在Flutter / dart的控制台中抛出错误
我已经通过使用删除了小吃店
return WillPopScope(
onWillPop: () async {
ScaffoldMessenger.of(context).removeCurrentSnackBar();
return true;
},child: Scaffold(...
但它也不起作用。
错误日志如下:
E/Flutter (13058): [ERROR:Flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/Flutter (13058): At this point the state of the widget's element tree is no longer stable.
E/Flutter (13058): 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.
我该如何解决这个问题?
解决方法
正如我从你的日志中看到的,这个问题是因为上下文没有被正确地传递给 WillPopScope
小部件,因为它被丢弃了
你能做的是
声明一个全局变量
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
然后像这样在您的 _scaffoldKey
上注册此 Scaffold
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,...
现在,无论何时您需要访问此上下文,您都可以使用 _scaffoldKey.currentContext
,例如在 ScaffoldMessenger.of
.. 部分
这应该可以解决您的问题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。