Search code examples
flutternavigationbottomnavigationview

Flutter Navigate to Independent screen from BottomNavigation bar


Following is my code which i am using for bottom navigation

class NaviBottom extends StatefulWidget {
  @override
  _NaviBottomState createState() => _NaviBottomState();
}

class _NaviBottomState extends State<NaviBottom> {
  int _currentIndex = 0;
  final List<Widget> _children = [
    HomeScreen(),
    AddProperties(),
    MyFavProperties(),
    MyProfile(),
    Login()
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Open Houze")),
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.blue,
        selectedItemColor: Colors.black,
        unselectedItemColor: Colors.white,
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        items: [
          BottomNavigationBarItem(
              icon: new Icon(Icons.home), title: new Text('First')),
          BottomNavigationBarItem(
              icon: new Icon(Icons.mail), title: new Text('Second')),
          BottomNavigationBarItem(
              icon: Icon(Icons.person), title: Text('Third')),
          BottomNavigationBarItem(
              icon: Icon(Icons.person), title: Text('Forth')),
          BottomNavigationBarItem(
              icon: Icon(Icons.person), title: Text('Fifith'))
        ],
      ),
    );
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}

In this my first three tab views to be shown with bottom navigation bar whereas when I click on the last two tabs I need to Navigate and show other screens without BottomNavigation bar,


Solution

  • void onTabTapped(int index) {
      if(index >= 0 && index < 3)
        setState(() {
          _currentIndex = index;
        });
      if(index == 3)
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => FourthPage()),
        );
      if(index == 4)
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => FifthPage()),
        );
    }
    

    N.B : Dart has type inference, meaning that you don't need to annotate the type if it's explicit. So you can just type final _children and remove the List<Widget>.