Magesh Pandian
Magesh Pandian

Reputation: 9369

how to handle switch page logic on back press in flutter

I am new to flutter, I handed back press event by onWillPop () to show alert dialog. But I need to show the alert dialog for home page only (like Are you want to exit?). In the code I have a type like current page if the current page is home, then only show Alert dialog or otherwise switch to home page.

Code

if(currentType == Home)
{
    showExitDialog();
}
else
{
   switchToHome();
}

Where can i handle this ?

Upvotes: 0

Views: 2185

Answers (1)

Tree
Tree

Reputation: 31371

set custom leading property on your app bar.

The default value is to go back one page, so if you dont set nothing, back arrow will be there and it will do Navigator.of(context).maybePop();

From Navigator docs

If this is null and [automaticallyImplyLeading] is set to true, the [AppBar] will imply an appropriate widget. For example, if the [AppBar] is in a [Scaffold] that also has a [Drawer], the [Scaffold] will fill this widget with an [IconButton] that opens the drawer (using [Icons.menu]). If there's no [Drawer] and the parent [Navigator] can go back, the [AppBar] will use a [BackButton] that calls [Navigator.maybePop].

But if you want to override it do this

on your home page

  appBar: AppBar(
    leading: IconButton(icon: Icon(Icons.exit_to_app),onPressed: (){
      exitTheApp();
    },),
  ),

on your other AppBars

  appBar: AppBar(
    leading: IconButton(icon: Icon(Icons.home),onPressed: (){
      showHomePage();
    },),
  ),

Upvotes: 2

Related Questions