Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Navigation Bar - Change tab from another page

I would like to be able to change the navigation bar tab programmatically. I have a button inside Page1 that navigates to Page2. When I perform this, the navigation bar disappears because I didn't select page2 using the navigation bar.

I have 4 dart files along the lines of navigationbar.dart, page1.dart, page2.dart, page3.dart

The Navigation page is the home page of the application with the children:

final List<Widget> _children = [
      Page1(),
      Page2(),
      Page3(),
    ];

return Scaffold(
      backgroundColor: Colors.black,
      body: _children[_selectedPage],
      bottomNavigationBar: _bottomNavigationBar(context),
      resizeToAvoidBottomPadding: true,
    );
like image 587
Bollie Avatar asked Dec 18 '22 16:12

Bollie


1 Answers

You have to change a TabControlller like this

1* Create TabController instance

TabController _tabController;

2* in initState methode use this

@override
void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 3);
  }

3* add a Mixin to _HomeState

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {....}

4* assign the TabController to your TabBar

TabBar(
      controller: _tabController,
      tabs: _yourTabsHere,
    ),

5* Pass controller to your Pages

TabBarView(
    controller: _tabController,
    children:<Widget> [
  Page1(tabController:_tabController),
  Page2(tabController:_tabController),
  Page3(tabController:_tabController),
];

6* call tabController.animateTo() from Page1

class Page1 extends StatefulWidget {
final TabController tabController
Page1({this.tabController});
....}

class _Page1State extends  State<Page1>{
....
onButtonClick(){
  widget._tabController.animateTo(index); //index is the index of the page your are intending to (open. 1 for page2)
}
}

Hope it helps

like image 124
Constantin N. Avatar answered Dec 28 '22 07:12

Constantin N.