[Flutter]ModalBottomSheetを閉じるには?

Flutter

どうも、ちょげ(@chogetarou)です。

ModalBottomSheetを閉じる方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

ModalBottomSheetを閉じるには、Navigator.of(context).pop()を使います。

具体的な方法としては、ModalBottomSheet内のボタンなどの処理で、Navigator.of(context).pop()を呼び出します。

TextButton(
  onPressed: () {
    Navigator.of(context).pop();
  },
  child: Text('Close'),
),

呼び出したタイミングでModalBottomSheetが閉じられます。

以下は、使用例です。

使用例
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            showModalBottomSheet(
              context: context,
              builder: (BuildContext context) {
                return Container(
                  child: TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text('Close'),
                  ),
                  alignment: Alignment.center,
                );
              },
            );
          },
          child: Text('Show'),
        ),
      ),
    );
  }

コメント

タイトルとURLをコピーしました