0

I use this drawer for each activity:

final MyDrawer _drawer = new MyDrawer();

class MyDrawer extends StatefulWidget {
  @override
  _MyDrawerState createState() => new _MyDrawerState();
}

class _MyDrawerState extends State<MyDrawer> {
  @override
  Widget build(BuildContext context) {
    return new Drawer(
      child: new ListView(
          children: <Widget> [
            new DrawerHeader(
              child: new Text("Header"),
            ),
            new ListTile(
              leading: new Icon(Icons.home),
              title: new Text("Home"),
              onTap: () {
                Navigator.popAndPushNamed(context, "/");
              },

            ),
            new ListTile(
                leading: new Icon(Icons.android),
                title: new Text("Another Page"),
                onTap: () {
                  Navigator.popAndPushNamed(context, AnotherPage.routeName);
                },

            ),new ListTile(
                leading: new Icon(Icons.email),
                title: new Text("Third Page"),
                onTap: () {
                  Navigator.popAndPushNamed(context, ThirdPage.routeName);
                }
            )
          ]
      ),
    );
  }
}

Each page is a statefull widget and they share the same drawer:

drawer: _drawer

I am looking for a way to have only one instance for activity instead to create a new activity each time a menu item is clicked, I tried:

ThirdPage.routeName: (BuildContext context) =>
        _thirdPage == null ? _thirdPage = new ThirdPage(title: "Third Page") : _thirdPage

And is it possible to adapt the drawer instance based on current activity?

paolo2988
  • 857
  • 3
  • 15
  • 31

1 Answers1

0

I suppose you are trying to implement singleton classes, i.e, class that have only one instance.

An example of a Singleton class:

class MyDrawer extends StatefulWidget{
  static final MyDrawer _drawer = new MyDrawer._internal();

  factory MyDrawer() {
    return _drawer;
  }

  MyDrawer._internal();

  @override
  Widget build(BuildContext context){
    return new Text("Drawer")
  }
}

For other ways to achieve singleton class in dart, you can take a look at the answers here.

Hope that helped!

Hemanth Raj
  • 32,555
  • 10
  • 92
  • 82