1

我正在尝试AlertDialog在 Dart 中制作一个可重用的并且能够制作一个。UI 显示并且运行良好。这段代码中唯一的问题是,当我按下保存按钮时,会出现以下错误:未处理的异常:类型“未来”不是“未来”类型的子类型。下面是我的AlertDialog课:

enum alertDialogAction { cancel, save }

class Dialogs {
  static Future<alertDialogAction> alertDialog(
    BuildContext context,
    String title,
    String body,
  ) {
    final action = showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            title: Text(title),
            content: Text(body),
            actions: <Widget>[
              FlatButton(
                  onPressed: () =>
                      Navigator.pop(context,alertDialogAction.cancel),
                  child: Text("cancel")),
              RaisedButton(
                  color: Colors.blueAccent,
                  onPressed: () =>
                      Navigator.of(context).pop(alertDialogAction.save),
                  child: Text(
                    "save",
                    style: TextStyle(color: Colors.white),
                  )),
            ],
          );
        });
    return (action != null) ? action : alertDialogAction.cancel;
  }
 }

这是我在 index.dart 中的称呼:

 final action=await Dialogs.alertDialog(context,"title", "body");
 if (action == alertDialogAction.save){
      //code runs
      }
4

1 回答 1

2

这是因为您Future<dynamic>通过声明同时将函数final action的返回类型指定为a来返回 a 。staticalertDialogFuture<alertDialogAction>

为避免将来出现此类问题,请始终为您声明的所有变量指定特定类型。

Future<alertDialogAction> action = showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            title: Text(title),
            content: Text(body),
            actions: <Widget>[
              FlatButton(
                  onPressed: () =>
                      Navigator.pop(context,alertDialogAction.cancel),
                  child: Text("cancel")),
              RaisedButton(
                  color: Colors.blueAccent,
                  onPressed: () =>
                      Navigator.of(context).pop(alertDialogAction.save),
                  child: Text(
                    "save",
                    style: TextStyle(color: Colors.white),
                  )),
            ],
          );
        });

并这样称呼

alertDialogAction action=await Dialogs.alertDialog(context,"title", "body");
于 2020-03-28T03:42:45.743 回答