跳到主内容

为屏幕添加抽屉导航

如何实现 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);
              },
            ),
          ],
        ),
      ),
    );
  }
}