[Flutter]Drawerを開くボタンを自作するには?

Flutter

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

Drawerを開くボタンを自作する方法を紹介します。

スポンサーリンク

方法

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

Drawerを開くボタンを自作するには、 ScffoldStateのGlobalKeyを使います。

まず、ScffoldStateのGlobalKeyを用意します。

var _scaffoldKey = GlobalKey<ScaffoldState>();

次に、用意したGlobalKeyをScaffoldの引数「key」に指定します。

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
    );
  }

そして、ボタンを追加し、タップ処理で「_scaffoldKey.currentState!.openDrawer()」を呼び出します。

ElevatedButton(
  onPressed: () {
    _scaffoldKey.currentState!.openDrawer();
  },
  child: Text('Drawerを開く'),
),

以下は、使用例です。

使用例
  var _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
       drawer: Drawer(
         child: Column(
           children: [
            DrawerHeader(
              child: Container(
                color: Colors.green,
              ),
            ),
            ListTile(
              title: Text('Item1'),
            ),
            ListTile(
              title: Text('Item2'),
            ),
            ListTile(
              title: Text('Item3'),
            ),
          ],
        ),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            _scaffoldKey.currentState!.openDrawer();
          },
          child: Text('Drawerを開く'),
        ),
      ),
    );
  }

コメント

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