如何在Flutter中制作AlertDialog?

时间:2018-12-19 03:10:48

标签: dart flutter flutter-alertdialog

我正在学习在Flutter中构建应用程序。现在我来警报对话框。我之前在AndroidiOS中都做了过这些操作,但是如何在Flutter中发出警报?

以下是一些相关的SO问题:

我想进行更一般的规范问答,所以下面是我的答案。

10 个答案:

答案 0 :(得分:11)

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

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

enter image description here

代码: 1. arr = arr.filter(obj=>'name' in obj);

const arr = [{
    "20": "Start Date:",
    "28": "15/06/2020",
},
{
    "name": "Jun/Jul 2020",
    "Monday 15th June": "Mon",

},
{
    "Monday 15th June": 15,
    "Tuesday 16th June": 16
},
{
    "name": "Charlie Sheen"
},
{
    "name": "Ray Liotta",
    "Thursday 18th June": "08:00-18:00:T5&6"
},
{
    "Thursday 18th June": "Theatres 5&6"
},
{
    "name": "Neil, Whatever"
},
{
    "3": "Theatres 1&2"
},
{
    "name": "Joe,  Bloggs",
    "Monday 15th June": "08:00-17:00:T1&2"
}];
const res = arr.filter(obj=>"name" in obj);
console.log(res);

您可以通过创建新方法(例如:

alertDialog_widget.dart

答案 1 :(得分:8)

一个按钮

Test1

两个按钮

showAlertDialog(BuildContext context) {

  // set up the button
  Widget okButton = FlatButton(
    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 = FlatButton(
    child: Text("Cancel"),
    onPressed:  () {},
  );
  Widget continueButton = FlatButton(
    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 = FlatButton( child: Text("Remind me later"), onPressed: () {}, ); Widget cancelButton = FlatButton( child: Text("Cancel"), onPressed: () {}, ); Widget launchButton = FlatButton( 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 = FlatButton( child: Text("Launch missile"), onPressed: () { Navigator.of(context).pop(); // dismiss dialog launchMissile(); }, ); ,则该按钮将被禁用。

null

enter image description here

补充代码

这里是onPressed: null, 的代码,以防您无法运行上述功能。

main.dart

答案 2 :(得分:6)

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

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
}
}

答案 3 :(得分:5)

只需使用此自定义对话框类,您无需将该字段保留为空或将其设置为null即可轻松进行此自定义。

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

答案 4 :(得分:4)

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

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();
          },
        ),
      ],
    );
  }
}

输出将类似于此

enter image description here

答案 5 :(得分:3)

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

称为:

private void FileSystemWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {

        var SyncTask = new Task(() => 
        {

            //DO A LOT OF WORK HERE
        });

        SyncTask.Start();

    }

答案 6 :(得分:2)

或者您可以使用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();

您还可以定义generic alert styles

*我是RFlutter Alert的开发人员之一。

答案 7 :(得分:2)

如果您想要漂亮且响应迅速的警报对话框,则可以使用

颤动警报,花哨对话框,丰富警报,甜警报对话框,简易对话框和简易警报

这些警报看起来不错且响应迅速。其中rflutter警报是最好的。目前,我正在为我的应用程序使用rflutter警报。

答案 8 :(得分:0)

签出Flutter Dropdown Banner可以轻松提醒用户事件和及时采取行动,而不必管理呈现,延迟和发布组件的复杂性。

要进行设置:

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),
    );
  }
}
点击here查看示例

答案 9 :(得分:0)

显示 Dialog 的另一个简单选项是使用 stacked_services

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