Drawer Widget in Flutter
The Drawer widget is used to as an additional sub-router that consists of various links to other routes (ie, pages) in the same application. It has a horizontal movement from the edge of the Scaffold that navigates the link to different routes in the flutter app. All children of a Drawer widget are usually in ListView and initially, only the DrawerHeader is present in the UI which when tapped extends horizontally.
Constructors:
Syntax: Drawer({Key key, double elevation: 16.0, Widget child, String semanticLabel})
Properties:
- child: The widgets below this widget in the tree.
- hashCode: The hash code for this object.
- key: Controls how one widget replaces another widget in the tree.
- runtimeType: A representation of the runtime type of the object.
- elevation: The z-coordinate at which to place this drawer relative to its parent.
- semanticLabel: The semantic label of the dialog used by accessibility frameworks to announce screen transitions when the drawer is opened and closed.
Example:
Dart
import 'package:flutter/material.dart' ; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { static const String _title = 'Drawer Example' ; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: MyStatefulWidget(), ); } } class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key key}) : super(key: key); @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { 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: const Text( 'GeeksForGeeks' ), backgroundColor: Colors.green, ), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: const <Widget>[ DrawerHeader( decoration: BoxDecoration( color: Colors.green, ), child: Text( 'Drawer Header' , style: TextStyle( color: Colors.white, fontSize: 24, ), ), ), ListTile( leading: Icon(Icons.message), title: Text( 'Messages' ), ), ListTile( leading: Icon(Icons.account_circle), title: Text( 'Profile' ), ), ListTile( leading: Icon(Icons.settings), title: Text( 'Settings' ), ), ], ), ), ); } } |
chevron_right
filter_none
Output:
Explanation:
- First, initialize the main app as a stateless widget.
- Second design the main widget as you desire.
- Build the Appbar with the scaffold widget.
- Now use the Drawer widget inside the body of the scaffold widget that is a child of the appbar.