Close modal bottom sheet programmatically in flutter

Short answer:

Use any of the below:

Navigator.pop(context);
Navigator.of(context).pop();

Long answer:

Generally there are 2 types of bottom sheet.

  1. showModalBottomSheet => Like a Dialog, not a part of Scaffold

  2. showBottomSheet => Part of Scaffold, this is persistent.


1. Showing and Hiding showModalBottomSheet

This code shows bottom sheet, and hides it when tapping on the FlutterLogo

@override
void initState() {
  super.initState();
  Future(() {
    showModalBottomSheet(
      context: context,
      builder: (_) {
        return GestureDetector(
          onTap: () => Navigator.of(context).pop(), // Closing the sheet.
          child: FlutterLogo(size: 200),
        );
      },
    );
  });
}

Output:

enter image description here


2. Showing and Hiding showBottomSheet

This code shows a button, which will open and close the bottom sheet.

late PersistentBottomSheetController _controller;
GlobalKey<ScaffoldState> _key = GlobalKey();
bool _open = false;
  
@override
Widget build(BuildContext context) {
  return Scaffold(
    key: _key,
    body: Center(
      child: ElevatedButton(
        onPressed: () {
          if (!_open) {
            _controller = _key.currentState!.showBottomSheet(
              (_) => SizedBox(
                child: FlutterLogo(size: 200),
                width: double.maxFinite,
              ),
            );
          } else {
            _controller.close();
          }
          setState(() => _open = !_open);
        },
        child: Text(_open ? "Close" : "Open"),
      ),
    ),
  );
}

Output:

enter image description here


Closing a ModalBottomSheet programmatically is done via

Navigator.pop(context);

So I just call that pop function inside the onTap callback function of the GestureDetector.

showModalBottomSheet(context: context, builder: (BuildContext context)
{
  return SingleChildScrollView(child:
    Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
      GestureDetector(onTap: () {
          Navigator.pop(context);
          doSomething();
        }, child:
        Text("Item 1")
      ),
      GestureDetector(onTap: () {
          Navigator.pop(context);
          doSomething();
        }, child:
        Text("Item 2")
      ),
    ]),
  );
});

Tags:

Dart

Flutter