gpt4 book ai didi

flutter - 未处理的异常: 'Future'类型不是 'Future'类型的子类型

转载 作者:行者123 更新时间:2023-12-03 03:23:11 32 4
gpt4 key购买 nike

我试图在Dart中创建一个可重用的AlertDialog,并且能够制作一个。 UI显示出来,并且运行良好。这段代码中的唯一问题是,当我按下“保存”按钮时,它会出现以下错误:未处理的异常:类型“Future”不是类型“Future”的子类型。下面是我的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
}

最佳答案

这是因为您在声明Future<dynamic>的同时将final action函数static的返回类型指定为alertDialog,从而返回了Future<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");

关于flutter - 未处理的异常: 'Future<dynamic>'类型不是 'Future<alertDialogAction>'类型的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60896772/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com