当零食栏显示在屏幕上并且同时按下后退按钮时,它会在控制台中以 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.. 部分

这应该可以解决您的问题