Flutter : CupertinoTabScaffold – Back button close app on Android from TabView's navigation

Issue

I have an App which uses CupertinoApp-CupertinoTabScaffold.

My App’s hierarchy

CupertinoApp
- CupertinoTabScaffold
-- CupertinoTabView
--- Home
---- Movie list
----- Movie Detail
--- Search
---- Movie Search List
----- Movie Detail
--- Profile
--- Settings

I just realized on Android when i click back button app closes even in Movie Detail (from any tab).

Back button should be really go back from Movie Detail.

I searched for 5 days and couldn’t find any solution or workaround this problem.

Best regards,

Utku Y.

Solution

I have been having this issue for a lot of time, after lot of searching i find this perfect solution: This solution is 100% accurate. I hope this helps.
We are taking help of Keys and I have added the code if you don’t understand something do ask me.

    ///these are KEYS which are assigned to every Tab,
///the problem of navigation is solved by these KEYS
final GlobalKey<NavigatorState> firstTabNavKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> secondTabNavKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> thirdTabNavKey = GlobalKey<NavigatorState>();

CupertinoTabController tabController;

@override
void initState() {
  // TODO: implement initState
  super.initState();
  tabController = CupertinoTabController(initialIndex: 0);
}

@override
Widget build(BuildContext context) {
  //making a list of the keys
  final listOfKeys = [firstTabNavKey, secondTabNavKey, thirdTabNavKey];

  List homeScreenList = [
    //list of different screens for different tabs
  ];
  return CupertinoApp(
    //this is important
    home: WillPopScope(
      onWillPop: () async {
        return !await listOfKeys[tabController.index].currentState.maybePop();
      },
      child: CupertinoTabScaffold(
        controller: tabController, //set tabController here
        tabBar: CupertinoTabBar(
          items: [
            ///this is where we are setting aur bottom ICONS
            BottomNavigationBarItem(
                label: 'AddClass',
                icon: Icon(CupertinoIcons.add_circled_solid)),
            BottomNavigationBarItem(
                label: 'Profile', icon: Icon(CupertinoIcons.person_solid)),
            BottomNavigationBarItem(
                label: 'Joined', icon: Icon(CupertinoIcons.xmark_circle_fill)),
          ],
          // currentIndex: pageIndex,
        ),
        tabBuilder: (
          context,
          index,
        ) {
          return CupertinoTabView(
            navigatorKey: listOfKeys[
                index], //set navigatorKey here which was initialized before
            builder: (context) {
              return homeScreenList[index];
            },
          );
        },
      ),
    ),
  );
} 

Answered By – Pulkit Prajapat

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.