A. Hn.
A. Hn.

Reputation: 11

How can I route to a new page using tabController?

Sorry if this sounds a bit obvious but this framework is still fairly unknown to me but I have created a bunch of other pages in my app (saved as .dart files) and also have created paths to them through the use of a drawer. I now have have a bottomNavigationBar that has 5 tabs. I want to be able to route to my previously created page using the tabs. I am currently using the defaultTabController.

bottomNavigationBar: Container(  
    color: Colors.grey[200],  
        child: Container(  
            margin: EdgeInsets.symmetric(vertical: 16),   
                child: TabBar(  
                    isScrollable: true  
                    labelColor: Colors.black,  
                    labelPadding: EdgeInsets.fromLTRB(21, 0, 21, 16),  
                    unselectedLabelColor: Colors.black45,  
                    indicatorColor: Colors.orange,  
                    indicatorPadding: EdgeInsets.fromLTRB(21, 0, 21, 16),  
                    labelStyle: TextStyle(  
                        fontSize: 16, fontWeight: FontWeight.bold  
                    ),  
                 tabs: <Tab>[  
                    new Tab(  
                       text: "Home",  
                   ),  
                    new Tab(  
                       text: "Page 1",  
                   ),  
                    new Tab(  
                       text: "Page 2",  
                   ),  
                    new Tab(  
                       text: "Page 3",  
                   ),  
                    new Tab(  
                       text: "Page 4",  
                ),  
              ],  
            ),  
          ),  
       ),  

For example, when someone clicks on the "Page 1" tab, I want to be able to route the user to my "page1.dart" file. Thanks in advance!

Upvotes: 1

Views: 452

Answers (1)

Armaan Sandhu
Armaan Sandhu

Reputation: 867

You do not need TabBar if you're using bottomNavigationBar. You can implement bottomNavigationBar by code below.

  int currentIndex = 0;
  List<Widget> children = [
    Home();
    Page1();
  ];

  onTapped(int index){
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          onTap: onTapped,
            currentIndex: currentIndex,
            items: [
              BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
              BottomNavigationBarItem(icon: Icon(Icons.add), title: Text('Page 1'))
            ]),
        body: children[currentIndex]);
  }

currentIndex will keep the record of the current opened tab. children is the List of pages you want to route in body. onTapped will change currentIndex to index of Navigation Bar.

Upvotes: 1

Related Questions