user18349414
user18349414

Reputation: 51

Flutter - How to take an action when the bottom modal sheet is dismissed?

I have a filters button. It's a container with a border, and inside are two icons in a row. All of this is wrapped in a gesture detector.

When the user taps the gesture detector, I am showing a bottom modal sheet. This all works. However, I want one of the icons to change depending on whether the user has the bottom modal sheet activated or not. How can I achieve this?

I think I can call setState once the button is tapped, BEFORE showing the modal bottom sheet. How can call setState again when the user taps out of it?

Thanks!

Is there an option to configure this in the showModalBottomSheet constructor?

Upvotes: 5

Views: 8149

Answers (2)

Mohamed Mansour
Mohamed Mansour

Reputation: 329

I was searching how to dismiss bottom sheet after navigation through it to a second screen , I found out that bottom sheet gets also added to navigation stack so , just use pushReplacement:

Navigator.pushReplacement( context,PageTransition(type: PageTransitionType.leftToRight, child: Page()));

hope this help someone.

Upvotes: 0

Guillaume Roux
Guillaume Roux

Reputation: 7298

As you did not post any code I'm guessing that you are using the method showModalBottomSheet.

This method has the following prototype:

Future<T?> showModalBottomSheet<T>({
  required BuildContext context,
  required WidgetBuilder builder,
  Color? backgroundColor,
  double? elevation,
  ShapeBorder? shape,
  Clip? clipBehavior,
  BoxConstraints? constraints,
  Color? barrierColor,
  bool isScrollControlled = false,
  bool useRootNavigator = false,
  bool isDismissible = true,
  bool enableDrag = true,
  RouteSettings? routeSettings,
  AnimationController? transitionAnimationController,
})

source

As you can see it returns a Future<T?> type which means that you can apply await, then or whenComplete to the returned future operation. In your case using whenComplete might be the better option if you don't need any value from the bottom sheet.

Example

showModalBottomSheet<void>(
  context: context,
  builder: (context) {
    return Container(
      height: 200,
      color: Colors.amber,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const Text('Modal BottomSheet'),
            ElevatedButton(
              child: const Text('Close BottomSheet'),
              onPressed: () => Navigator.pop(context),
            )
          ],
        ),
      ),
    );
  },
).whenComplete(_onBottomSheetClosed);
void _onBottomSheetClosed() {
  print("Closed bottomsheet");
}

Try the full example on DartPad

Upvotes: 5

Related Questions