How to make an AlertDialog in Flutter?

前端 未结 9 2788
小蘑菇
小蘑菇 2020-11-29 00:56

I am learning to build apps in Flutter. Now I have come to alert dialogs. I have done them before in Android and iOS, but how do I make an alert in Flutter?

Here are

9条回答
  •  -上瘾入骨i
    2020-11-29 01:02

    Simply used this custom dialog class which field you not needed to leave it or make it null so this customization you got easily.

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

    Usage:

    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);
    

    Output:

提交回复
热议问题