Flutter Navigation Bar - Change tab from another page

烂漫一生 提交于 2020-08-24 02:02:55

问题


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,
    );

回答1:


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




回答2:


in the button :

onPressed: (){ 
    _currentIndex = 1;
   //or which value you want 
    setState((){});
}

in the bottom Navigation bar :

currentIndex = _currentIndex



回答3:


You can Use IndexStack.

Demostration.



来源:https://stackoverflow.com/questions/57560751/flutter-navigation-bar-change-tab-from-another-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!