Close modal bottom sheet programmatically in flutter

后端 未结 4 2052
迷失自我
迷失自我 2020-12-25 09:23

I am displaying a BottomSheet via showModalBottomSheet() and inside several widgets with a GestureDetector. I would like to see the BottomSheet clos

4条回答
  •  清歌不尽
    2020-12-25 10:14

    Generally there are 2 types of bottom sheet.

    (I) showModalBottomSheet // works like Dialog, not a part of Scaffold

    (II) showBottomSheet // this is a part of Scaffold


    Showing and Hiding showModalBottomSheet

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

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

    Output:


    Showing and Hiding showBottomSheet

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

    PersistentBottomSheetController _controller;
    GlobalKey _key = GlobalKey();
    bool _open = false;
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        key: _key,
        body: Center(
          child: RaisedButton(
            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:

提交回复
热议问题