How to make an AlertDialog in Flutter?

前端 未结 9 2836
小蘑菇
小蘑菇 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条回答
  •  悲&欢浪女
    2020-11-29 01:27

    I used similar approach, but I wanted to

    1. Keep the Dialog code as a widget in a separated file so I can reuse it.
    2. Blurr the background when the dialog is shown.

    Code: 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: [
            new FlatButton(
              child: new Text("Continue"),
               onPressed: () {
                continueCallBack();
              },
            ),
            new FlatButton(
              child: Text("Cancel"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
          ));
      }
    }
    

    You can call this in main (or wherever you want) by creating a new method like:

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

提交回复
热议问题