在 Material Design 设计准则里,主要提供了两种导航方式:Tab 和 Drawer。 当没有足够的空间来支持 tab 导航时,drawer 提供了另一个方便的选择。
在 Flutter中,我们可以将 Drawer Widget 与 Scaffold 结合使用来创建一个具有 Material Design 风格的 Drawer 布局。
步骤
创建一个
Scaffold添加一个 drawer
向 drawer 中添加内容
通过编程关闭 drawer
1. 创建一个 Scaffold
为了向应用中添加一个 Drawer,我们需要将其放在 Scaffold Widget 中。 Scaffold Widget 为遵循 Material 设计守则的应用程序提供了一套统一的可视化结构。它同样支持一些特殊的 Material Design 组件,例如 Drawer,AppBar 和 SnackBar 等。
在这个例子中,我们想要创建一个带有 drawer 的 Scaffold:
Scaffold(drawer: // We'll add our Drawer here in the next step!);
2. 添加一个 drawer
我们现在可以在 Scaffold 上添加一个 drawer。虽然 drawer 可以是任何 Widget,但最好还是使用 material library 中的 Drawer Widget,因为这样才符合 Material Design 设计规范。
Scaffold(drawer: Drawer(child: // We'll populate the Drawer in the next step!));
3. 向 drawer 中添加内容
既然已经有了一个 Drawer,我们现在就可以向其中添加内容。在这个例子中,我们将使用 ListView。虽然你也可以使用 Column Widget,但是 ListView 在这种情况下将是更好的选择,因为如果内容所占用的空间超出了屏幕的话,它将能够允许用户进行滚动。
我们将使用 DrawerHeader 和两个 ListTile Widget 填充 ListView。有关使用 List 的更多信息,请参阅 list recipes。
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: <Widget>[DrawerHeader(child: Text('Drawer Header'),decoration: BoxDecoration(color: Colors.blue,),),ListTile(title: Text('Item 1'),onTap: () {// Update the state of the app// ...},),ListTile(title: Text('Item 2'),onTap: () {// Update the state of the app// ...},),],),);
4. 通过编程关闭 drawer
我们经常需要在用户点击某个项目后,就将 Drawer 关掉。那么怎样才能做到这一点呢?请使用 Navigator!
当用户打开 Drawer 时,Flutter 会将 drawer Widget 覆盖在当前的导航堆栈上。 因此,要关闭 drawer,我们可以通过调用 Navigator.pop(context) 来实现。
ListTile(title: Text('Item 1'),onTap: () {// Update the state of the app// ...// Then close the drawerNavigator.pop(context);},),
一个完整的例子
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {final appTitle = 'Drawer Demo';@overrideWidget build(BuildContext context) {return MaterialApp(title: appTitle,home: MyHomePage(title: appTitle),);}}class MyHomePage extends StatelessWidget {final String title;MyHomePage({Key key, this.title}) : super(key: key);@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text(title)),body: Center(child: Text('My Page!')),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: <Widget>[DrawerHeader(child: Text('Drawer Header'),decoration: BoxDecoration(color: Colors.blue,),),ListTile(title: Text('Item 1'),onTap: () {// Update the state of the app// ...// Then close the drawerNavigator.pop(context);},),ListTile(title: Text('Item 2'),onTap: () {// Update the state of the app// ...// Then close the drawerNavigator.pop(context);},),],),),);}}
