在採用 Material Design 的應用中,有兩種主要的導航選項:標籤頁和抽屜選單。當空間不足以支援標籤頁時,抽屜選單提供了一個方便的替代方案。

在 Flutter 中,結合使用 Drawer 元件和 Scaffold 元件來建立帶有 Material Design 抽屜選單的佈局。本示例將透過以下步驟完成:

  1. 建立一個 Scaffold
  2. 新增一個抽屜選單。
  3. 用專案填充抽屜選單。
  4. 以程式設計方式關閉抽屜選單。

1. 建立一個 Scaffold

#

要嚮應用新增抽屜選單,請將其包裹在 Scaffold 元件中。Scaffold 元件為遵循 Material Design 規範的應用提供了一致的視覺結構。它還支援特殊的 Material Design 元件,例如抽屜選單、應用欄和訊息條。

在此示例中,建立一個帶有 drawerScaffold

dart
Scaffold(
  appBar: AppBar(title: const Text('AppBar without hamburger button')),
  drawer: // Add a Drawer here in the next step.
);

2. 新增一個抽屜選單

#

現在,將抽屜選單新增到 Scaffold。抽屜選單可以是任何元件,但通常最好使用 material 庫中的 Drawer 元件,它遵循 Material Design 規範。

dart
Scaffold(
  appBar: AppBar(title: const Text('AppBar with hamburger button')),
  drawer: Drawer(
    child: // Populate the Drawer in the next step.
  ),
);

3. 用專案填充抽屜選單

#

現在你已經有了一個 Drawer,接下來向其中新增內容。在此示例中,使用 ListView。雖然你可以使用 Column 元件,但 ListView 很方便,因為它允許使用者在內容超出螢幕支援的空間時滾動瀏覽抽屜選單。

使用 DrawerHeader 和兩個 ListTile 元件填充 ListView。有關使用列表的更多資訊,請參閱列表示例

dart
Drawer(
  // Add a ListView to the drawer. This ensures the user can scroll
  // through the options in the drawer if there isn't enough vertical
  // space to fit everything.
  child: ListView(
    // Important: Remove any padding from the ListView.
    padding: EdgeInsets.zero,
    children: [
      const DrawerHeader(
        decoration: BoxDecoration(color: Colors.blue),
        child: Text('Drawer Header'),
      ),
      ListTile(
        title: const Text('Item 1'),
        onTap: () {
          // Update the state of the app.
          // ...
        },
      ),
      ListTile(
        title: const Text('Item 2'),
        onTap: () {
          // Update the state of the app.
          // ...
        },
      ),
    ],
  ),
);

4. 以程式設計方式開啟抽屜選單

#

通常,你不需要編寫任何程式碼來開啟 drawer,因為當 leading 元件為 null 時,AppBar 中的預設實現是 DrawerButton

但如果你想自由控制 drawer。你可以透過使用 Builder 呼叫 Scaffold.of(context).openDrawer() 來實現。

dart
Scaffold(
  appBar: AppBar(
    title: const Text('AppBar with hamburger button'),
    leading: Builder(
      builder: (context) {
        return IconButton(
          icon: const Icon(Icons.menu),
          onPressed: () {
            Scaffold.of(context).openDrawer();
          },
        );
      },
    ),
  ),
  drawer: Drawer(
    child: // Populate the Drawer in the last step.
  ),
);

5. 以程式設計方式關閉抽屜選單

#

使用者點選一個專案後,你可能希望關閉抽屜選單。你可以透過使用 Navigator 來實現。

當用戶開啟抽屜選單時,Flutter 會將抽屜選單新增到導航堆疊。因此,要關閉抽屜選單,請呼叫 Navigator.pop(context)

dart
ListTile(
  title: const Text('Item 1'),
  onTap: () {
    // Update the state of the app
    // ...
    // Then close the drawer
    Navigator.pop(context);
  },
),

互動示例

#

此示例展示了在 Scaffold 元件中使用的 Drawer。該 Drawer 有三個 ListTile 項。_onItemTapped 函式改變所選專案的索引,並在 Scaffold 的中心顯示相應的文字。

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const appTitle = 'Drawer Demo';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle = TextStyle(
    fontSize: 30,
    fontWeight: FontWeight.bold,
  );
  static const List<Widget> _widgetOptions = <Widget>[
    Text('Index 0: Home', style: optionStyle),
    Text('Index 1: Business', style: optionStyle),
    Text('Index 2: School', style: optionStyle),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        leading: Builder(
          builder: (context) {
            return IconButton(
              icon: const Icon(Icons.menu),
              onPressed: () {
                Scaffold.of(context).openDrawer();
              },
            );
          },
        ),
      ),
      body: Center(child: _widgetOptions[_selectedIndex]),
      drawer: Drawer(
        // Add a ListView to the drawer. This ensures the user can scroll
        // through the options in the drawer if there isn't enough vertical
        // space to fit everything.
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: [
            const DrawerHeader(
              decoration: BoxDecoration(color: Colors.blue),
              child: Text('Drawer Header'),
            ),
            ListTile(
              title: const Text('Home'),
              selected: _selectedIndex == 0,
              onTap: () {
                // Update the state of the app
                _onItemTapped(0);
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Business'),
              selected: _selectedIndex == 1,
              onTap: () {
                // Update the state of the app
                _onItemTapped(1);
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('School'),
              selected: _selectedIndex == 2,
              onTap: () {
                // Update the state of the app
                _onItemTapped(2);
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}