我在静态方法中有AlertDialog
,因为当用户单击OK
按钮时,我想获取回调。
我尝试使用typedef
,但听不懂。
下面是我的代码:
class DialogUtils{
static void displayDialogOKCallBack(BuildContext context, String title,
String message)
{
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(title, style: normalPrimaryStyle,),
content: new Text(message),
actions: <Widget>[
new FlatButton(
child: new Text(LocaleUtils.getString(context, "ok"), style: normalPrimaryStyle,),
onPressed: () {
Navigator.of(context).pop();
// HERE I WANTS TO ADD CALLBACK
},
),
],
);
},
);
}
}
您只需单击OK
即可等待对话框被取消{returns null}或关闭,在这种情况下,将返回true
class DialogUtils {
static Future<bool> displayDialogOKCallBack(
BuildContext context, String title, String message) async {
return await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(title, style: normalPrimaryStyle,),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text(LocaleUtils.getString(context, "ok"), style: normalPrimaryStyle,),
onPressed: () {
Navigator.of(context).pop(true);
// true here means you clicked ok
},
),
],
);
},
);
}
}
然后,当您呼叫displayDialogOKCallBack
时,应以await
作为结果
示例:
onTap: () async {
var result =
await DialogUtils.displayDialogOKCallBack();
if (result == false) {
// Ok button is clicked
}
}
然后为将来的工作使用回调函数:
DialogUtils.displayDialogOKCallBack().then((value) {
if (value) {
// Do stuff here when ok button is pressed and dialog is dismissed.
}
});