How to make an AlertDialog in Flutter?

前端 未结 9 2794
小蘑菇
小蘑菇 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:18

    If you need a dialog with only one button:

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

    If you need a dialog with Yes/No buttons:

    onPressed: () async {
    bool result = await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('Confirmation'),
          content: Text('Do you want to save?'),
          actions: [
            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
    }
    }
    

提交回复
热议问题