Flutter、showDialog 和 Future.delayed

Flutter, showDialog and Future.delayed

我试过构建这个:

child: GestureDetector(
 onTap: () {
  return showDialog(
   context: context,
   builder: (BuildContext context) {
    return AlertDialog(
     content: Text('Some text'),
     actions: <Widget>[
       TextButton(
          child: Text('Yes'),
          onPressed: () async {
           await myFunc(context);
 },
),

这是 myFunc 的代码:

Future myFunc(BuildContext context) async {
  await Future.delayed(Duration(seconds: 2));
  Navigator.of(context).pop();
  showErrorDialog(context); //return new showDialog
}

现在可以正常工作,但我想在延迟之前弹出第一个 showDialog,我尝试这样:

Future myFunc(BuildContext context) async {
  Navigator.of(context).pop();
  await Future.delayed(Duration(seconds: 2));
  showErrorDialog(context); //return new showDialog
}

现在没有调用 showErrorDialog,我得到以下信息:

E/flutter ( 9151): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter ( 9151): At this point the state of the widget's element tree is no longer stable.
E/flutter ( 9151): 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.
E/flutter ( 9151): #0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3864:9)
E/flutter ( 9151): #1      Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3878:6)
E/flutter ( 9151): #2      Element.dependOnInheritedWidgetOfExactType (package:flutter/src/widgets/framework.dart:3893:12)
E/flutter ( 9151): #3      Localizations.of (package:flutter/src/widgets/localizations.dart:472:48)
E/flutter ( 9151): #4      debugCheckHasMaterialLocalizations.<anonymous closure> (package:flutter/src/material/debug.dart:70:23)
E/flutter ( 9151): #5      debugCheckHasMaterialLocalizations (package:flutter/src/material/debug.dart:91:4)
E/flutter ( 9151): #6      showDialog (package:flutter/src/material/dialog.dart:1049:10)
...

如何在延迟之前调用 pop 而不会出错?

像这样更改您的函数:

我的函数:

Future myFunc(BuildContext ctx , BuildContext context) async {
  Navigator.pop(ctx);
  await Future.delayed(Duration(seconds: 2));
  showErrorDialog(context);
}

手势检测器:

child: GestureDetector(
 onTap: () {
  return showDialog(
   context: context,
   builder: (BuildContext ctx) {
    return AlertDialog(
     content: Text('Some text'),
     actions: <Widget>[
       TextButton(
          child: Text('Yes'),
          onPressed: () async {
           await myFunc(ctx ,context);
 },
),