Reputation: 517
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,
);
Upvotes: 4
Views: 10036
Reputation: 3046
You can do that using a GlobalKey.
var bottomNavigatorKey = GlobalKey<State<BottomNavigationBar>>();
put that key in widget,
new BottomNavigationBar(
key: bottomNavigatorKey,
items: [...],
onTap: (int index) {...},
),
put below lines in change tab method,
BottomNavigationBar navigationBar = bottomNavigatorKey.currentWidget as BottomNavigationBar;
navigationBar.onTap(1);
Upvotes: 2
Reputation: 2839
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
Upvotes: 14
Reputation: 496
in the button :
onPressed: (){
_currentIndex = 1;
//or which value you want
setState((){});
}
in the bottom Navigation bar :
currentIndex = _currentIndex
Upvotes: 0