在使用 Material Design 的应用中,导航有两种主要选择:标签页和抽屉。当空间不足以支持标签页时,抽屉提供了一个便捷的替代方案。

在 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 很有用,因为它允许用户在内容占用空间超出屏幕范围时滚动抽屉。

使用一个 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);
  },
),

互动示例

#

此示例展示了 DrawerScaffold 组件中的用法。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);
              },
            ),
          ],
        ),
      ),
    );
  }
}