I have a showModalBottomSheet
like the below, which I understand to inherit from BottomSheet
(right?)
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Container(
height: 260.0,
child: Text('I am text')
);
},
);
What I want to do:
I want to know (listen) when the modal is being closed, and act on it.
I've seen this onClosing
callback:
https://docs.flutter.io/flutter/material/BottomSheet/onClosing.html
How can I have a listener attached to the showModalBottomSheet
, and then act accordingly when it fires?
showBottomSheet does not return a future, now it returns a PersistentBottomSheetController
Perhaps it's not the best solution, but showModalBottomSheet return a "Future" so you can used it.
For example:
Using async / await on showModalBottomSheet() close
You can do this with async / await instead of callbacks.
As per the documentation, showModalBottomSheet()
This means that we can "await" the
showModelBottomSheet()
to complete, and then use the value returned by theNavigator.pop()
function used to close the sheet.Because this is "waiting" for the sheet to be closed, your next function won't run until it's closed. In this example, we just call the
print()
function, but that could be any function you need. No callbacks are necessary in this case.Tip: if it's critical that the user tap a "save and close" button to close the bottom sheet (instead of just tapping outside of it), you should use
isDismissibile: false
on the sheet.In this example, we expect the sheet to return a string when it's closed.
Example Button To Open The showModalBottomSheet()
Example Button To Close The sheet, inside Widget()
Example Log Outputs
I personally think the accepted answer is not as sleek as it can be. A wiser idea is to do it native Dart way without any extra complexity:
It also works with
Navigator.of(context).pushNamed()
.result
variable value in my case is defined by the value you pass back onNavigator.of(context).pop({value})
. You can return any kind of object and then make a simple if statement to make sure data is the one you want:Old post but anyways, Might be helpful for you or others. So you can also achieve it by use of
whenComplete
function ofshowModalBottomSheet
.Let's see below code
That's it.