Search code examples
dartflutternavigation-drawer

Flutter side drawer as a widget


I am trying to implement side drawer as a widget in my flutter app

home.dart

import '../widgets/navigation_drawer_widget.dart'; //imported the nav drawer class from widgets directory

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(length: 2,
        child: Scaffold(
          drawer: DrawerWidget(),
          appBar: AppBar(
            title: Text('Home'),
            bottom: TabBar(tabs: <Widget>[
              Tab(
                icon: Icon(Icons.access_time),
                text: 'Tab 1',
              ),
              Tab(
                icon: Icon(Icons.calendar_today),
                text: 'Tab 2',
              )
            ]),
          ),
          body: TabBarView(children: <Widget>[
            Tab1(),
            Tab2()
          ]),
        )
    );
  }
}

my drawer widget ** navigation_drawer_widget.dart** file

import 'package:flutter/material.dart';

class DrawerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        AppBar(
          automaticallyImplyLeading: false,
          title: Text('Menu'),
        ),
        ListTile(
          leading: Icon(Icons.home),
          title: Text('Home'),
          onTap: () {
            Navigator.pushReplacementNamed(context, '/home');
          },
        ),
        ListTile(
          leading: Icon(Icons.person),
          title: Text('My Profile'),
          onTap: () {
            Navigator.pushReplacementNamed(context, '/profile');
          },
        ),
        ListTile(
          leading: Icon(Icons.school),
          title: Text('My Education'),
          onTap: () {
            Navigator.pushReplacementNamed(context, '/education');
          },
        ),
      ],
    );
  }
}

But when I click the nav hamburger icon it shows me something like this

enter image description here

As you can see the nav drawer becomes transparent and extends to the full width of the page. If I move the drawer code to the home page (instead of doing DrawerWidget() ) it will show the regular good ol nav drawer.

Any idea whats happening here?


Solution

  • You need to wrap the Column in the DrawerWidget with a Drawer if you want default material design drawer.

    From the doc:

    A drawer could be any Widget, but it’s often best to use the Drawer widget from the material library, which adheres to the Material Design spec.

    https://flutter.io/cookbook/design/drawer/