跳到主內容

為螢幕新增抽屜導航

如何實現 Material 側邊欄 (Drawer)。

在遵循 Material Design 的應用中,有兩種主要的導航方式:標籤頁 (tabs) 和側邊欄 (drawers)。當空間不足以容納標籤頁時,側邊欄是一個方便的替代方案。

在 Flutter 中,將 Drawer 元件與 Scaffold 結合使用,即可建立帶有 Material Design 側邊欄的佈局。本示例採用以下步驟:

  1. 建立一個 Scaffold
  2. 新增側邊欄。
  3. 在側邊欄中填充內容。
  4. 透過程式碼關閉側邊欄。

1. 建立一個 Scaffold

#

要為應用新增側邊欄,請將其包裹在 Scaffold 元件中。Scaffold 元件為遵循 Material Design 指南的應用提供了統一的視覺結構。它還支援各種 Material Design 特有元件,例如 Drawers(側邊欄)、AppBars(應用欄)和 SnackBars(底部提示欄)。

在此示例中,建立一個帶有 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 非常好用,因為它允許使用者在內容超出螢幕範圍時進行滾動。

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

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);
              },
            ),
          ],
        ),
      ),
    );
  }
}