Sag*_*ala 5 function callback flutter flutter-alertdialog
我有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
},
),
],
);
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地等待对话框被关闭 {returns null} 或通过单击关闭OK,在这种情况下,将返回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
},
),
],
);
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后当你打电话时displayDialogOKCallBack你应该await得到结果
例子:
onTap: () async {
var result =
await DialogUtils.displayDialogOKCallBack();
if (result) {
// Ok button is clicked
}
}
Run Code Online (Sandbox Code Playgroud)