text
stringlengths
1
474
Now that you have a Drawer in place, add content to it.
For this example, use a ListView.
While you could use a Column widget,
ListView is handy because it allows users to scroll
through the drawer if the
content takes more space than the screen supports.Populate the ListView with a DrawerHeader
and two ListTile widgets.
For more information on working with Lists,
see the list recipes.
<code_start>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.
// ...
},
),
],
),
);<code_end>
<topic_end>
<topic_start>
4. Close the drawer programmatically
After a user taps an item, you might want to close the drawer.
You can do this by using the Navigator.When a user opens the drawer, Flutter adds the drawer to the navigation
stack. Therefore, to close the drawer, call Navigator.pop(context).
<code_start>ListTile(
title: const Text('Item 1'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),<code_end>
<topic_end>
<topic_start>
Interactive example
This example shows a Drawer as it is used within a Scaffold widget.
The Drawer has three ListTile items.
The _onItemTapped function changes the selected item’s index
and displays the corresponding text in the center of the Scaffold.info Note
For more information on implementing navigation,
check out the Navigation section of the cookbook.
<code_start>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,
),