Flutter 导航栏 - 从另一个页面更改选项卡 [英] Flutter Navigation Bar - Change tab from another page
问题描述
我希望能够以编程方式更改导航栏选项卡.我在 Page1 中有一个导航到 Page2 的按钮.当我执行此操作时,导航栏会消失,因为我没有使用导航栏选择 page2.
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.
我有 4 个 dart 文件,分别是 navigationbar.dart、page1.dart、page2.dart、page3.dart
I have 4 dart files along the lines of navigationbar.dart, page1.dart, page2.dart, page3.dart
Navigation 页面是包含子项的应用程序的主页:
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,
);
推荐答案
你必须改变一个 TabController 像这样
You have to change a TabControlller like this
1* 创建 TabController 实例
1* Create TabController instance
TabController _tabController;
2* 在 initState 方法中使用这个
2* in initState methode use this
@override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: 3);
}
3* 添加一个 Mixin 到 _HomeState
3* add a Mixin to _HomeState
class _HomeState extends State<Home> with SingleTickerProviderStateMixin {....}
4* 将 TabController 分配给您的 TabBar
4* assign the TabController to your TabBar
TabBar(
controller: _tabController,
tabs: _yourTabsHere,
),
5* 将控制器传递给您的页面
5* Pass controller to your Pages
TabBarView(
controller: _tabController,
children:<Widget> [
Page1(tabController:_tabController),
Page2(tabController:_tabController),
Page3(tabController:_tabController),
];
6* 从 Page1 调用 tabController.animateTo()
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)
}
}
希望对你有帮助
这篇关于Flutter 导航栏 - 从另一个页面更改选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!