flutter showdialog async
In Flutter, the showDialog
function is used to display a dialog box on the screen. It is an asynchronous operation, meaning that it returns a Future
. You can use the async/await
keywords to work with the Future
and write asynchronous code.
Here is an example of how to use the showDialog
function with async/await
:
<button onPressed="showAlertDialog">
Show Dialog
</button>
void showAlertDialog() async {
final result = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Dialog Title"),
content: Text("Dialog Content"),
actions: <Widget>[
FlatButton(
child: Text("Cancel"),
onPressed: () {
Navigator.of(context).pop(false);
},
),
FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop(true);
},
),
],
);
},
);
// Use the result returned by showDialog
if (result) {
print("User clicked OK");
} else {
print("User clicked Cancel");
}
}
The above example shows a Flutter button. When pressed, it invokes the showAlertDialog
function. Inside this function, showDialog
is called with the context
and a builder
function. The builder
function returns an AlertDialog
widget, which is then displayed on the screen.
The showDialog
function returns a Future
that resolves to the result of the dialog (e.g., true
if the user clicks OK, or false
if the user clicks Cancel). By using await
with the showDialog
function call, the execution of the code is paused until the dialog is closed.
Once the dialog is closed, the value returned by the dialog (stored in the result
variable) can be used in further logic. In this example, if the user clicks OK, the message "User clicked OK" is printed, and if the user clicks Cancel, the message "User clicked Cancel" is printed.