Presenting Bottom Sheet using ViewModel in Flutter
My new app uses a bottom sheet to create a new party and the bottom sheet leverages data from the view model of the screen.
The bottom sheet is also huge and embedded in the screen code. So I decided to separate the sheet to an individual widget.
Widget
First I created a new widget containing entire widgets to present the popup.
class PartyCreatePopupView extends StatefulWidget
View Model
I want to separate not only popup widget, but view model also. So I defined view model too and property to it.
class PartyCreatePopupViewModel extends ChangeNotifier
...
class PartyCreatePopupView extends StatefulWidget {
final PartyCreatePopupViewModel viewModel;
Child View Model
The screen use view model using ChangeNotifierProvider, but I don’t want to use it in the popup view again and I hope to manage the view model of the popup by owner, the screen view model.
So I create Create Popup View Model with parameters given by the screen.
onPressPartyCreatePopupOpen() {
partyCreatePopupViewModel = PartyCreatePopupViewModel(
placeList: placeList, onPressCreate: onPressPartyCreate);
}
The screen’s bottom sheet is just going to use it.
viewModel.onPressPartyCreatePopupOpen();
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return PartyCreatePopupView(
viewModel:
viewModel.partyCreatePopupViewModel!);
}
)
Pop
I realized that popup still live while testing the create feature. So I am going to add code to close the popup. There is no method like dismiss in SwiftUI. We can close it just using Navigator.pop() same to screens on the stack.
Navigator.of(context).pop();
Clearing Child View Model
After creating or when dismissing to cancel, the popup view model should be cleared. We know when the creation is finished. But if users close the popup by tapping dimmed background. I don’t know.
Fortunately showModalBottomSheet has a method to solve it. We can get callback using whenComplete
. So I observes the complete event and make invoke of clearPartyCreatPopup
method.
clearPartyCreatePopup() {
partyCreatePopupViewModel = null;
}
showModalBottomSheet(...
).whenComplete(viewModel.clearPartyCreatePopup);
If you found this post helpful, please give it a round of applause 👏. Explore more Flutter-related content in my other posts.