超时后关闭`showModalBottomSheet`

时间:2020-05-29 21:56:01

标签: flutter

我试图通过事件监听器关闭showModalBottomSheet小部件。

          showModalBottomSheet(
              useRootNavigator: true,
              context: context,
              builder: (newcontext) {
                return MyBottomDialog();
              });

我试图通过事件监听器将其关闭:

class _MyBottomDialogState extends State<MyBottomDialog> {
...
...
  void initState() {
    _myEventStream.listen((state) {
      if (state == 'timeout') {
        Navigator.of(context, rootNavigator: true).pop();
      }
    });
    super.initState();
  }

TypeError: Cannot read property 'findAncestorStateOfType' of null
.
.
.
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.

我该如何实现?

2 个答案:

答案 0 :(得分:0)

流类实际上带有timeout method。您只需要提供一个持续时间,如果持续时间超过该持续时间,则将抛出TimeoutException。将执行结果包装在try块中,然后也许从on TimeoutException catch (e)块中调用close modal sheet方法。

答案 1 :(得分:0)

可能是我没有正确捕获错误所表示的内容。 即使关闭对话框后,流订阅仍然存在。因此,即使未打开对话框,也会调用处理程序。

在小部件的_streamSubscription.cancel()方法中添加dispose可以解决此问题。