I am creating an app and I want to show a dialog for the user which contains a slider to pick a value.
the problem comes here, I want to get the value of that slider which user picked and deal with it.
I am using the dialog as a stateful widget and everything works okay except returning the value as I've mentioned.
class Dialog extends StatefulWidget {
@override
_DialogState createState() => _DialogState();
final double val;
Dialog({this.val,});
}
class _DialogState extends State<Dialog> {
double value = 0;
@override
void initState() {
super.initState();
value = widget.val;
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Slider(
value: value,
min: 0,
max: 100,
onChanged: (va) {
setState(() {
value = va;
});
},
),
);
}
}
show dialog code
double vale = 0;
-------
() async {
await showDialog(
context: context,
builder: (context) => Dialog(
val: vale,
),
);
}
In its on the pressed property, we have to use the showDialog widget of flutter. It takes context and a builder. In builder, we provide the AlertDialog widget with title, content(Description of a title), and actions (Yes or no buttons), and our alert dialog box is ready to use.
How do you give a dialog radius in flutter? To display rounded corners for AlertDialog in Flutter, specify the shape property of AlertDialog with RoundedRectangleBorder object with border radius specified. An AlertDialog with rounded corners having a border radius of 30 is shown in the following screenshot.
In Flutter, the AlertDialog is a widget, which informs the user about the situations that need acknowledgment. The Flutter alert dialog contains an optional title that displayed above the content and list of actions displayed below the content.
What is missing is that you need to return the value when closing the dialog, like this:
return AlertDialog(
title: Slider(
value: value,
min: 0,
max: 100,
onChanged: (va) {
setState(() {
value = va;
});
},
),
actions: [
ElevatedButton(
onPressed: () => Navigator.pop(context),
child: Text('cancel')),
ElevatedButton(
onPressed: () => Navigator.pop(context, value),
child: Text('confirm')),
],
);
It will then be returned by the showDialog function as expected as a Future
You can access and use the value that comes from your dialog option like this:
showDialog(
context: context,
builder: (context) => Dialog(
val: vale,
),
).then((valueFromDialog){
// use the value as you wish
print(valueFromDialog);
});
The .then()
will be triggered after the user selects an option on your Dialog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With