I have this piece of code:
child: CircleAvatar(
radius: 18,
backgroundColor: Colors.white70,
child: IconButton(
icon: Icon(Icons.camera_alt_outlined),
onPressed: () => selectPhoto(),
),
)
And when the icon is pressed I'd like to have a simple dialog with a couple of options, so I wrote this:
selectPhoto() {
return SimpleDialog(
title: const Text('Create Post'),
children: <Widget>[
SimpleDialogOption(...),
SimpleDialogOption(...),
SimpleDialogOption(...)
],
);
}
But when I try to run the app, nothing happens. What did I do wrong? How to solve? Ty
CodePudding user response:
The return value of your function is not being used to anything. It's no use to return a SimpleDialog
in a onPressed
. The onPressed function will be called by the Widget so it's useless to give it a returning value.
Following the documentation, your function needs to call the showDialog
method:
- Change your
selectPhoto
function:
await showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Create Post'),
children: <Widget>[
SimpleDialogOption(...),
SimpleDialogOption(...),
SimpleDialogOption(...)
],
);
})
The showDialog method shows the dialog you created. If you want, you can store the result in its return value:
var result = await showDialog(
[...]
This way you can check which option was pressed. If the user cancels the dialog (e.g. by hitting the back button on Android, or tapping on the mask behind the dialog) then the future completes with the null value.
You can read more examples at the Flutter doc's linked in this answer.
CodePudding user response:
showDialog return future your method selectPhoto
should be async and your code should be like this
Future<void> selectPhoto() async {
await showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Select assignment'),
children: <Widget>[
SimpleDialogOption(...),
SimpleDialogOption(...),
SimpleDialogOption(...)
],
);
},
);
}
for more info visit the official doc