'How to implement a drawer on Flutter that closes itself when tapped on the option that's already displayed?

I'm trying to implement a drawer that closes itself if the user taps on the option which the app is currently showing. My implementation was:

int currentPageIndex = 0;
void pageLoader(BuildContext context, int pageIndex){
    switch(pageIndex){
      case 0:
        if(currentPageIndex != 0){
          currentPageIndex = 0;
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const Page0())
          );
        } else {
          Navigator.pop(context);
        }
        break;
      case 1:
        if(currentPageIndex != 1){
          currentPageIndex = 1;
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const Page1())
          );
        } else {
          Navigator.pop(context);
        }
        break;
      ...
    }
  }

And the onTap properties of my listtiles are in this format:

onTap: () => pageLoader(context, index) //index being a number

This approach bugs out when the user taps the back button, since the displayed page changes without changing the currentPageIndex variable. How can I write a better solution?



Solution 1:[1]

First, create a ScaffoldState key

GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

Scaffold(
  key: _scaffoldKey,)

At the place where you are handling the Tap thing after that line writes the below code also.

For the left drawer

toggleDrawer() async {
  if (_scaffoldKey.currentState.isDrawerOpen) {
    _scaffoldKey.currentState.openEndDrawer();
  } else {
    _scaffoldKey.currentState.openDrawer();
  }
}

For the right drawer

toggleDrawer() async {
  if (_scaffoldKey.currentState.isDrawerOpen) {
    _scaffoldKey.currentState.openDrawer();
  } else {
    _scaffoldKey.currentState.openEndDrawer();
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shailesh Mishra