如何在扑动中创建一个 AlertDialog?

我正在 Flutter 学习开发应用程序。现在我来提醒对话。我以前在 abc0和 abc1中也这样做过,但是如何在 Flutter 发出警报呢?

下面是一些相关的问题:

我想做一个更一般的规范问答,所以我的答案在下面。

270454 次浏览

一个按钮

showAlertDialog(BuildContext context) {


// set up the button
Widget okButton = TextButton(
child: Text("OK"),
onPressed: () { },
);


// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("My title"),
content: Text("This is my message."),
actions: [
okButton,
],
);


// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}

两个按钮

showAlertDialog(BuildContext context) {


// set up the buttons
Widget cancelButton = TextButton(
child: Text("Cancel"),
onPressed:  () {},
);
Widget continueButton = TextButton(
child: Text("Continue"),
onPressed:  () {},
);


// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("AlertDialog"),
content: Text("Would you like to continue learning how to use Flutter alerts?"),
actions: [
cancelButton,
continueButton,
],
);


// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}

三个按钮

showAlertDialog(BuildContext context) {


// set up the buttons
Widget remindButton = TextButton(
child: Text("Remind me later"),
onPressed:  () {},
);
Widget cancelButton = TextButton(
child: Text("Cancel"),
onPressed:  () {},
);
Widget launchButton = TextButton(
child: Text("Launch missile"),
onPressed:  () {},
);


// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Notice"),
content: Text("Launching this missile will destroy the entire universe. Is this what you intended to do?"),
actions: [
remindButton,
cancelButton,
launchButton,
],
);


// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}

操作按钮

上面示例中按钮的 onPressed回调是空的,但是您可以添加如下内容:

Widget launchButton = TextButton(
child: Text("Launch missile"),
onPressed:  () {
Navigator.of(context).pop(); // dismiss dialog
launchMissile();
},
);

如果回调 null,则按钮将被禁用。

onPressed: null,

enter image description here

补充代码

以下是 main.dart的代码,以防您没有得到上面的函数来运行。

import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter'),
),
body: MyLayout()),
);
}
}


class MyLayout extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
child: Text('Show alert'),
onPressed: () {
showAlertDialog(context);
},
),
);
}
}


// replace this function with the examples above
showAlertDialog(BuildContext context) { ... }

或者你可以使用 RFlutter Alert 库。它易于定制和易于使用。它的默认样式包括圆角,您可以添加按钮,如果你想要的。

基本警示:

Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();

按钮提示:

Alert(
context: context,
type: AlertType.error,
title: "RFLUTTER ALERT",
desc: "Flutter is more awesome with RFlutter Alert.",
buttons: [
DialogButton(
child: Text(
"COOL",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () => Navigator.pop(context),
width: 120,
)
],
).show();

您还可以定义 通用警报样式通用警报样式

我是 RFlutter Alert 的开发者之一 * 。

使用 下拉横幅可以轻松地提醒用户事件和提示操作,而不必管理呈现、延迟和丢弃组件的复杂性。

安排一下:

import 'packages:dropdown_banner/dropdown_banner.dart';
...
class MainApp extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
final navigatorKey = GlobalKey<NavigatorState>();
...
return MaterialApp(
...
home: DropdownBanner(
child: Scaffold(...),
navigatorKey: navigatorKey,
),
);
}
}

使用方法:

import 'packages:dropdown_banner/dropdown_banner.dart';
...
class SomeClass {
...
void doSomethingThenFail() {
DropdownBanner.showBanner(
text: 'Failed to complete network request',
color: Colors.red,
textStyle: TextStyle(color: Colors.white),
);
}
}
单击 给你查看示例

您可以使用此代码段创建一个双按钮警报框,

import 'package:flutter/material.dart';


class BaseAlertDialog extends StatelessWidget {


//When creating please recheck 'context' if there is an error!


Color _color = Color.fromARGB(220, 117, 218 ,255);


String _title;
String _content;
String _yes;
String _no;
Function _yesOnPressed;
Function _noOnPressed;


BaseAlertDialog({String title, String content, Function yesOnPressed, Function noOnPressed, String yes = "Yes", String no = "No"}){
this._title = title;
this._content = content;
this._yesOnPressed = yesOnPressed;
this._noOnPressed = noOnPressed;
this._yes = yes;
this._no = no;
}


@override
Widget build(BuildContext context) {
return AlertDialog(
title: new Text(this._title),
content: new Text(this._content),
backgroundColor: this._color,
shape:
RoundedRectangleBorder(borderRadius: new BorderRadius.circular(15)),
actions: <Widget>[
new FlatButton(
child: new Text(this._yes),
textColor: Colors.greenAccent,
onPressed: () {
this._yesOnPressed();
},
),
new FlatButton(
child: Text(this._no),
textColor: Colors.redAccent,
onPressed: () {
this._noOnPressed();
},
),
],
);
}
}

要显示对话框,可以有一个方法在导入 BaseAlertDialog 类之后调用它 NB

_confirmRegister() {
var baseDialog = BaseAlertDialog(
title: "Confirm Registration",
content: "I Agree that the information provided is correct",
yesOnPressed: () {},
noOnPressed: () {},
yes: "Agree",
no: "Cancel");
showDialog(context: context, builder: (BuildContext context) => baseDialog);
}

输出是这样的

Output

如果你想要漂亮和响应警报对话框,然后你可以使用颤振包像

漂亮的对话框,丰富的对话框,甜蜜的对话框,简单的对话框和简单的对话框

这些警报看起来不错,反应灵敏。其中颤振警报是最好的。目前我正在使用我的应用程序的 rflutter 警报。

showAlertDialog(BuildContext context, String message, String heading,
String buttonAcceptTitle, String buttonCancelTitle) {
// set up the buttons
Widget cancelButton = FlatButton(
child: Text(buttonCancelTitle),
onPressed: () {},
);
Widget continueButton = FlatButton(
child: Text(buttonAcceptTitle),
onPressed: () {


},
);


// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text(heading),
content: Text(message),
actions: [
cancelButton,
continueButton,
],
);


// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}

叫做:

showAlertDialog(context, 'Are you sure you want to delete?', "AppName" , "Ok", "Cancel");

下面是一段较短但完整的代码。

如果您需要一个只有一个按钮的对话框:

await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Message'),
content: Text(
'Your file is saved.'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(); // dismisses only the dialog and returns nothing
},
child: new Text('OK'),
),
],
),
);

如果您需要一个带有“是”/“否”按钮的对话框:

onPressed: () async {
bool result = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Confirmation'),
content: Text('Do you want to save?'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(false); // dismisses only the dialog and returns false
},
child: Text('No'),
),
FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(true); // dismisses only the dialog and returns true
},
child: Text('Yes'),
),
],
);
},
);


if (result) {
if (missingvalue) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text('Missing Value'),
));
} else {
saveObject();
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
} else {
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}

我用了类似的方法,但我想

  1. 将对话框代码作为一个小部件保存在一个单独的文件中,因此 我可以重复使用
  2. 当对话框显示时,模糊背景。

enter image description here

密码: 1. alertDialog_widget.dart

import 'dart:ui';
import 'package:flutter/material.dart';




class BlurryDialog extends StatelessWidget {


String title;
String content;
VoidCallback continueCallBack;


BlurryDialog(this.title, this.content, this.continueCallBack);
TextStyle textStyle = TextStyle (color: Colors.black);


@override
Widget build(BuildContext context) {
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
child:  AlertDialog(
title: new Text(title,style: textStyle,),
content: new Text(content, style: textStyle,),
actions: <Widget>[
new FlatButton(
child: new Text("Continue"),
onPressed: () {
continueCallBack();
},
),
new FlatButton(
child: Text("Cancel"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
));
}
}

您可以通过创建如下新方法在 main (或任何您想要的地方)中调用它:

 _showDialog(BuildContext context)
{


VoidCallback continueCallBack = () => {
Navigator.of(context).pop(),
// code on continue comes here


};
BlurryDialog  alert = BlurryDialog("Abort","Are you sure you want to abort this operation?",continueCallBack);




showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}

简单地使用这个自定义对话框类,您不需要离开它或使其为空,这样就可以轻松地进行自定义。

import 'package:flutter/material.dart';


class CustomAlertDialog extends StatelessWidget {
final Color bgColor;
final String title;
final String message;
final String positiveBtnText;
final String negativeBtnText;
final Function onPostivePressed;
final Function onNegativePressed;
final double circularBorderRadius;


CustomAlertDialog({
this.title,
this.message,
this.circularBorderRadius = 15.0,
this.bgColor = Colors.white,
this.positiveBtnText,
this.negativeBtnText,
this.onPostivePressed,
this.onNegativePressed,
})  : assert(bgColor != null),
assert(circularBorderRadius != null);


@override
Widget build(BuildContext context) {
return AlertDialog(
title: title != null ? Text(title) : null,
content: message != null ? Text(message) : null,
backgroundColor: bgColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(circularBorderRadius)),
actions: <Widget>[
negativeBtnText != null
? FlatButton(
child: Text(negativeBtnText),
textColor: Theme.of(context).accentColor,
onPressed: () {
Navigator.of(context).pop();
if (onNegativePressed != null) {
onNegativePressed();
}
},
)
: null,
positiveBtnText != null
? FlatButton(
child: Text(positiveBtnText),
textColor: Theme.of(context).accentColor,
onPressed: () {
if (onPostivePressed != null) {
onPostivePressed();
}
},
)
: null,
],
);
}
}

用法:

var dialog = CustomAlertDialog(
title: "Logout",
message: "Are you sure, do you want to logout?",
onPostivePressed: () {},
positiveBtnText: 'Yes',
negativeBtnText: 'No');
showDialog(
context: context,
builder: (BuildContext context) => dialog);

产出:

enter image description here

另一个显示 Dialog 的简单选项是使用 堆叠服务

 _dialogService.showDialog(
title: "Title",
description: "Dialog message Tex",
);
});

这段代码可以工作并演示如何获取用户按下的按钮值:

import 'package:flutter/material.dart';


void main() => runApp(const MyApp());


class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);


static const String _title = 'Flutter Code Sample';


@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatelessWidget(),
),
),
);
}
}


class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);


@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
// set up the buttons
Widget cancelButton = TextButton(
child: Text("Cancel"),
onPressed: () => Navigator.pop(context, 'Cancel'),
);
Widget continueButton = TextButton(
child: Text("Ok"),
onPressed: () => Navigator.pop(context, 'Ok'),
);
showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('AlertDialog Title'),
content: const Text('AlertDialog description'),
actions: <Widget>[
cancelButton,
continueButton,
],
),
).then((value) => print(value));
},
child: const Text('Show Dialog'),
);
}
}

按确定按钮。然后取消按钮打印 enter image description here

enter image description here

警报对话框的最小代码

showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Title'),
content: Text(
'Content widget',
),
),
);
        `showDialog<String>(
context: context,
builder: (BuildContext context) =>
AlertDialog(
title: const Text(
'Invalid Password',
style: TextStyle(color: Colors.red),
),
content:
const Text('Create Strong Password'),
actions: <Widget>[
Center(
child: TextButton(
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors
.red, // Background Color
),
onPressed: () => Navigator.pop(
context, 'Cancel'),
child: const Text('Cancel'),
),
),
],
),
),`

再补充一点,我找到的最好的答案是:

自适应对话框: ^ 1.8.0 + 1

对于一个 OK 按钮,我发现最好的事情是使用 showOkAlertDialog

实施方法:

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';


Widget build(BuildContext context) {
return Container(
child: Center(
child: IconButton(
icon: Icon(
Icons.info,
),
onPressed: () => showOkAlertDialog(
context: context,
okLabel: 'OK',
title: 'Title',
message: 'This is the message',
),
)),
);
}

当你点击“确定”时清理并解散。

如果你需要一个对话框,这个代码为你。只要使用 showDialog() onPress或任何内部的一个函数。

 void showDialog() {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Login Failed!"),
content: const Text(
"Invalid credential !! Please check your email or password",
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w400),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: Container(
child: const Text(
"Try again",
style: TextStyle(color: Colors.cyan, fontSize: 17),
),
),
),
],
),
)}

演示对话框截图

希望能有所帮助

我使用的简单而有效的解决方案: < em > 享受 //示例可用于应用程序的退出对话框

ShowAlertDialog (BuildContext 上下文){

    Widget okButton = TextButton(
child: const Text("Leave now",style: TextStyle(color: Colors.red),),
onPressed: () { SystemNavigator.pop(); },
);


Widget nopeButton = TextButton(
child: const Text("Stay here"),
onPressed: () { Navigator.pop(context); },
);


AlertDialog alert = AlertDialog(
title: const Text("Leave"),
content: const Text("Are you sure you want to leave?"),
actions: [
nopeButton,
okButton,
],
);


showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}