Flutter 导航栏 - 从另一个页面更改选项卡

Bol*_*lie 4 navigation dart flutter

我希望能够以编程方式更改导航栏选项卡。我在 Page1 中有一个导航到 Page2 的按钮。当我执行此操作时,导航栏消失,因为我没有使用导航栏选择 page2。

我有 4 个 dart 文件,沿着 navigationbar.dart、page1.dart、page2.dart、page3.dart

导航页面是带有孩子的应用程序的主页:

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

return Scaffold(
      backgroundColor: Colors.black,
      body: _children[_selectedPage],
      bottomNavigationBar: _bottomNavigationBar(context),
      resizeToAvoidBottomPadding: true,
    );
Run Code Online (Sandbox Code Playgroud)

Con*_* N. 11

您必须像这样更改TabController

1* 创建 TabController 实例

TabController _tabController;
Run Code Online (Sandbox Code Playgroud)

2* 在 initState 方法中使用这个

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

3* 将 Mixin 添加到 _HomeState

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {....}
Run Code Online (Sandbox Code Playgroud)

4* 将 TabController 分配给您的 TabBar

TabBar(
      controller: _tabController,
      tabs: _yourTabsHere,
    ),
Run Code Online (Sandbox Code Playgroud)

5* 将控制器传递给您的页面

TabBarView(
    controller: _tabController,
    children:<Widget> [
  Page1(tabController:_tabController),
  Page2(tabController:_tabController),
  Page3(tabController:_tabController),
];
Run Code Online (Sandbox Code Playgroud)

6* 从 Page1 调用 tabController.animateTo()

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)
}
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你