flutter TabBar+TabView的使用

第一步 添加数据

List<TabTitle> tabList = [
    new TabTitle('推荐', 10),
    new TabTitle('热点', 0),
    new TabTitle('社会', 1),
    new TabTitle('娱乐', 2),
    new TabTitle('体育', 3),
    new TabTitle('美文', 4),
    new TabTitle('科技', 5),
    new TabTitle('财经', 6),
    new TabTitle('时尚', 7)
];

第二步 完成布局

class HomeState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  TabController mController;
  List<TabTitle> tabList;
  @override
  void initState() {
    super.initState();
    initTabData();
    mController = TabController(
      length: tabList.length,
      vsync: this,
    );
  }
  
  @override
  void dispose() {
    super.dispose();
    mController.dispose();
  }
  
  initTabData() {
    tabList = [
      new TabTitle('推荐', 10),
      new TabTitle('热点', 0),
      new TabTitle('社会', 1),
      new TabTitle('娱乐', 2),
      new TabTitle('体育', 3),
      new TabTitle('美文', 4),
      new TabTitle('科技', 5),
      new TabTitle('财经', 6),
      new TabTitle('时尚', 7)
    ];
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("首页"),
        backgroundColor: Color(0xffd43d3d),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.all_inclusive),
        backgroundColor: Color(0xffd43d3d),
        elevation: 2.0,
        highlightElevation: 2.0,
        onPressed: () {},
      ),
      body: Column(
        children: <Widget>[
          Container(
            color: new Color(0xfff4f5f6),
            height: 38.0,
            child: TabBar(
              isScrollable: true,
              //是否可以滚动
              controller: mController,
              labelColor: Colors.red,
              unselectedLabelColor: Color(0xff666666),
              labelStyle: TextStyle(fontSize: 16.0),
              tabs: tabList.map((item) {
                return Tab(
                  text: item.title,
                );
              }).toList(),
            ),
          ),
          Expanded(
            child: TabBarView(
              controller: mController,
              children: tabList.map((item) {
                return Stack(children: <Widget>[
                  Align(alignment:Alignment.topCenter,child: Text(item.title),),
                ],);
              }).toList(),
            ),
          )
        ],
      ),
    );
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 什么事听多了就烦
    啦啦啦cfy阅读 1,040评论 3 0
  • 何必呢 何必去假装 饿了就吃 困了便睡 你是独立的个体 抱歉 抱歉 我不是情感专家 并不会理性分析 或是软言细雨安...
    scumalapert阅读 2,187评论 6 4
  • 生活告诉我们,唯一能证明做事儿的就是结果。所以,一切表象和外在,都在行为举止中。
    吕明超阅读 1,033评论 0 0
  • 要尽可能用简单的的词汇描述自己的想法,要向身边的人说,像新人说,看别人是否能听懂。还有就是洞察力,先是用户面临那些...
    倪希嘎阅读 3,584评论 0 0