Flutter 应用之TabBar

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lin962792501/article/details/83109304

       本文记录Flutter开发的TabBar使用。 TabBar是选项切换页的意思,在android中通常是使用ViewPage来实现。在Flutter中,TabBar是被定义在Material Component中,所以他的使用需要在MaterialApp中。

      为了让TabBar能正常使用,需要保持选项卡和内容同步,这个工作是由TabController来完成的。可以手动创建一个TabController,也可以使用默认的 DefaultTabController部件。

      一、使用DefaultController

     

new MaterialApp(
      home: new DefaultTabController(length: 3, child: new Scaffold(
        appBar: new AppBar(
          title: new Text('DefaultTabController'),
          bottom: new TabBar(tabs: <Widget>[
            new Tab(text: '1'),
            new Tab(text: '2'),
            new Tab(text: '3'),
          ]),
        ),
        body: new TabBarView(children: <Widget>[
          new Icon(Icons.more),
          new Icon(Icons.more),
          new Icon(Icons.more),
        ]),
      )),
    );

       

二、使用自定义的TabController

class _MyTabBarState extends State<MyTabBar>
    with SingleTickerProviderStateMixin {
  var _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: 4, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("TabBar"),
          elevation: 0.7,
          bottom: new TabBar(
            controller: _tabController,
            indicator: new UnderlineTabIndicator(),
            tabs: <Widget>[
              new Tab(
                icon: new Icon(Icons.camera_alt),
              ),
              new Tab(
                text: "CHATS",
              ),
              new Tab(
                text: "STATUS",
              ),
              new Tab(
                text: "CALLS",
              ),
            ],
          ),
        ),
        body: new TabBarView(controller: _tabController, children: <Widget>[
          new Center(),
          new Center(),
          new Center(),
          new Center(),
        ]));
  }
}

      代码都很简单,可以看到他们都使用到了MaterialApp,Scaffold,TabBar,TabBarView。

猜你喜欢

转载自blog.csdn.net/lin962792501/article/details/83109304