我正在使用下面的代码注册用户,有一个上传图片的选项,如果为null,则不会注册用户,即可以正常工作,我唯一要面对的就是图片是{ {1}}应该向用户显示警报对话框,但是警报对话框根本不起作用。 我应该如何实施警报对话框?
curl -d '{json}' -H 'Content-Type: application/json' https://example.com
答案 0 :(得分:5)
您需要使用函数showDialog
以便出现对话框:
else {
print("Please Upload the Image");
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Image Required"),
content: Text("Please upload the image"),
actions: <Widget>[
FlatButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
};
);
}
答案 1 :(得分:0)
Peter Haddad的答案解决了这个问题,但是我建议将AlertDialog放在小部件中,这样很容易再次使用AlertDialog。这是我为项目执行的操作:
Dialogs.dart:
import 'package:flutter/material.dart';
enum alertDialogAction { cancel, save }
class Dialogs {
static Future<alertDialogAction> alertDialog(
BuildContext context,
String title,
String body,
String cancel,
String save,
) {
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.orange,
onPressed: () =>
Navigator.of(context).pop(alertDialogAction.save),
child: Text(
save,
style: TextStyle(color: Colors.white),
)),
],
);
});
return (action != null) ? action : alertDialogAction.cancel;
}
这里是您如何称呼它:
onPressed:() async {
final action= await Dialogs.alertDialog(context,"Title","Body","Cancel","Save");
//cancel and save are the button text for cancel and save operation
if(action==alertDialogAction.save){
//do something
Navigator.pop(context);
}
}
答案 2 :(得分:0)
您还可以使用支架显示对话框,例如,
Scaffold.of(context).showSnackBar(SnackBar(content: AlertDialog(content: Text('Alert!!!'))));
但是您必须牢记上下文应该是当前的支架。 因此,您可能希望将body属性(在Scaffold中)包装在Builder Widget中,然后在该Builder Widget中使用上下文时,该上下文将是当前的Scaffold。
答案 3 :(得分:0)
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Your Title!!!"),
content: Text("Your Content!!!"),
actions: <Widget>[
FlatButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
};
);