如何使用tabController路由到新页面?

时间:2018-12-25 22:40:36

标签: dart flutter

对不起,如果听起来有些明显,但是我仍然不知道这个框架,但是我在应用中创建了很多其他页面(另存为.dart文件),并且还通过使用抽屉。我现在有一个带有5个标签的bottomNavigationBar。我希望能够使用标签路由到我先前创建的页面。我目前正在使用defaultTabController。

bottomNavigationBar: Container(  
    color: Colors.grey[200],  
        child: Container(  
            margin: EdgeInsets.symmetric(vertical: 16),   
                child: TabBar(  
                    isScrollable: true  
                    labelColor: Colors.black,  
                    labelPadding: EdgeInsets.fromLTRB(21, 0, 21, 16),  
                    unselectedLabelColor: Colors.black45,  
                    indicatorColor: Colors.orange,  
                    indicatorPadding: EdgeInsets.fromLTRB(21, 0, 21, 16),  
                    labelStyle: TextStyle(  
                        fontSize: 16, fontWeight: FontWeight.bold  
                    ),  
                 tabs: <Tab>[  
                    new Tab(  
                       text: "Home",  
                   ),  
                    new Tab(  
                       text: "Page 1",  
                   ),  
                    new Tab(  
                       text: "Page 2",  
                   ),  
                    new Tab(  
                       text: "Page 3",  
                   ),  
                    new Tab(  
                       text: "Page 4",  
                ),  
              ],  
            ),  
          ),  
       ),  

例如,当某人单击“页面1”选项卡时,我希望能够将用户路由到我的“ page1.dart”文件。预先感谢!

1 个答案:

答案 0 :(得分:1)

如果您使用的是TabBar,则不需要bottomNavigationBar。您可以通过以下代码实现bottomNavigationBar。

  int currentIndex = 0;
  List<Widget> children = [
    Home();
    Page1();
  ];

  onTapped(int index){
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          onTap: onTapped,
            currentIndex: currentIndex,
            items: [
              BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
              BottomNavigationBarItem(icon: Icon(Icons.add), title: Text('Page 1'))
            ]),
        body: children[currentIndex]);
  }

currentIndex将保留当前打开的标签页的记录。 children是您要在正文中路由的页面列表。 onTapped会将currentIndex更改为导航栏的索引。