1. 程式人生 > >Flutter 應用之TabBar

Flutter 應用之TabBar

       本文記錄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。