1

I am making a flutter application in which flow is something like this: Splash screen where it will be checked whether user is login or not. If not login then go to Login screen else go to Main screen. Main screen has bottom navigation with three tabs and each tab his own navigators and in each navigator it may be possible that some screen may not be showing bottom bar. So I coded this till now.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter',
      home: Splash(),
      routes: <String, WidgetBuilder>{
        '/main_tab':  (context) => new MainScreen(),
         '/login':  (context) => new Login(),
      },
    );
  }
}

Now the MainScreen which has bottom tabs is like this.

class MainScreen extends StatefulWidget {
  @override
  _MainScreenState createState() => new _MainScreenState();
}

class _MainScreenState extends State<MainScreen>{
  final _navigatorKey = GlobalKey<NavigatorState>();
  int _selectedIndex = 0;
  int _lastIndex = 0;

  void _onItemTapped(int index) {
     if(index == 0) _navigatorKey.currentState.pushNamed('/');
     else if(index == 1) _navigatorKey.currentState.pushNamed('/page1');
     else if(index == 2) _navigatorKey.currentState.pushNamed('/page2');
    setState(() {
      _lastIndex = _selectedIndex;
      _selectedIndex = index;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WillPopScope(
        onWillPop: () async {
          if(_selectedIndex == 0) SystemNavigator.pop();
          else if (_navigatorKey.currentState.canPop()) {
             _navigatorKey.currentState.pop();
             setState(() {
               _selectedIndex = _lastIndex;
              // _lastIndex = _selectedIndex;
             });
              return false;
           }
          return true;
        },
        child: Navigator(
          key: _navigatorKey,
          initialRoute: '/',
            onGenerateRoute: (RouteSettings settings) {
              WidgetBuilder builder;
              // Manage your route names here
              switch (settings.name) {
                case '/':
                  builder = (BuildContext context) => Page1();
                  break;
                case '/page1':
                  builder = (BuildContext context) => Page2();
                  break;
                case '/page2':
                  builder = (BuildContext context) => Page3();
                  break;
                default:
                  throw Exception('Invalid route: ${settings.name}');
              }
              return MaterialPageRoute(
                builder: builder,
                settings: settings,
              );
            }
        ),
      ),
      bottomNavigationBar:BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Business'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('School'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
        type: BottomNavigationBarType.fixed,
      ),
    );
  }
}

Everything is working fine according to my requirements. To navigate to screen without bottom bar I was having some issue but I managed it by using rootnavigator:true and declaring that route in MainApp(). Now, concern is that when I press back button then screen pop up was working fine but it didn't changes the bottom bar selected index. So I put logic in willPop but thats not working fine. So please tell me how can I handle back press in bottom bar and also it should change the selected tab of the bottom bar.

1 Answer 1

0

In one of the projects I worked on I had to do the same. Application had bottom navigation, some pages were pushing using root navigator. For handling back action I did this:

WillPopScope(
  onWillPop: () async {
    bool canPop = await appFlows[currentTabIndex]
        .navigatorKey
        .currentState
        .maybePop();
    if (canPop) {
      return false;
    }
    if (currentTabIndex != 0) {
      navigateToTab(0);
      return false;
    }
    return true;
  },
  child: ...,
)

This way if the tab's navigation stack has more than one screen, then it will pop that screen. If user is in the root screen of a tab and presses back, user will be sent to main tab. And if user is in the root screen of main tab and presses back, Flutter will handle that and exits from app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.