text
stringlengths
1
372
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,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(title: text(widget.title)),
body: center(
child: _widgetOptions[_selectedIndex],
),