Flutter 側邊彈出的 Menu - Drawer


#Flutter#Flutter Widget#Drawer#Side Menu

Flutter 製作時遇到需要從側邊彈出的選單時可以使用 Scaffold + Drawer 來實現。

使用方法


要將 Drawer 加入到 APP 的話需要使用 Scaffold,有分為左邊的 drawer 與右邊的 endDrawer,可依照需求加到你的頁面內。

Scaffold(
    drawer: const Drawer(), // 左邊
    endDrawer: const Drawer(), // 右邊
)

ScaffoldState 內有提供 openDraweropenEndDrawercloseDrawercloseEndDrawer 四種 function 提供外部操作 Drawer 展開/收合。只要在 Scaffold 加上 GlobalKey 即可使用。
延伸 - Flutter 在父 Widget 呼叫子 Widget State Function

final GlobalKey<ScaffoldState> _myKey = GlobalKey();
_myKey.currentState!.openDrawer();
_myKey.currentState!.openEndDrawer();
_myKey.currentState!.closeDrawer();
_myKey.currentState!.closeEndDrawer();

若有使用 AppBar 那 Flutter 會自動在對應的位置新增一個 menu icon button,如需隱藏 icon button 左右邊有不同的設定:
左邊:AppBarautomaticallyImplyLeading 設定為 false
右邊:AppBaractions 設定為不為空的 List<Widget>

AppBar(
  automaticallyImplyLeading: true, // 左邊的 icon button 可將此設定為 false 即可隱藏
  actions: [], // 右邊的 icon button 需要使用非空 List 覆蓋
)

範例


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final GlobalKey<ScaffoldState> _myKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Demo Drawer'),
          automaticallyImplyLeading: true, // 左邊的 icon button 可將此設定為 false 即可隱藏
          actions: [], // 右邊的 icon button 需要使用非空 List 覆蓋
        ),
        key: _myKey,
        drawer: const Drawer(child: Center(child: Text('左邊'))),
        endDrawer: const Drawer(child: Center(child: Text('右邊'))),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () => _myKey.currentState!.openDrawer(),
                child: const Text('< 開啟左邊的 Drawer'),
              ),
              const SizedBox(height: 15),
              ElevatedButton(
                onPressed: () => _myKey.currentState!.openEndDrawer(),
                child: const Text('開啟右邊的 Drawer >'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

試試看吧:https://dartpad.dev/?id=190b5773f572ccdf88450b6dbde4c6bd


參考:
https://docs.flutter.dev/cookbook/design/drawer
https://stackoverflow.com/questions/55080091