Search code examples
flutterdartmodal-dialogfuturenavigator

How can I control what is passed to Navigator.pop() when clicking outside of a showModalBottomSheet?


I launch a modal bottom sheet, then use the data that is returned as its future.

var modalFuture = showModalBottomSheet(
                // ...
              );
              modalFuture.then((data) {
                // Use data
              });

I return data to it from the modal widget with:

Navigator.pop(context, data);

This is working well when completing the modal interaction with a widget I've set up. I encounter my issue when clicking outside of the modal. Clicking outside of the modal causes the modal to dismiss automatically (with a Navigator.pop(context) call?). I am okay with this closing interaction, but I would like to send data back with it (with a Navigator.pop(context, data) call). Is there anyway to override the implicit pop when clicking outside of a showModalBottomSheet modal?


Solution

  • You can wrap your ModalWidget with WillPopScope. You can see the example below

     WillPopScope(
      onWillPop: () async {
        Navigator.pop(context, data);
        return true; // return true if needs to be popped
      },
      child: ModelWidget(
        …
      ),
    );
    

    This will ensure that Navigator.pop is called when auto popped using the back button.