美文网首页
Flutter 之 TabBar 控件

Flutter 之 TabBar 控件

作者: Goach | 来源:发表于2019-09-25 11:12 被阅读0次

TabBar 控件,类似 Android 里面的 TabLayout 控件,直接看例子:

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  final List<String> _tabList = [
    '推荐',
    '科技',
    '视频',
    '历史',
    '深圳',
    '热点',
    '娱乐',
    '健康',
    '财经',
    '汽车',
    '新时代',
  ];
  TabController _tabController;
  VoidCallback onChanged;
  int _currentIndex = 0;
  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: _tabList.length, vsync: this);
    onChanged = () {
      setState(() {
        _currentIndex = this._tabController.index;
        print("_currentIndex===$_currentIndex");
      });
    };
    _tabController.addListener(onChanged);
  }
  @override
  void dispose() {
    _tabController.removeListener(onChanged);
    _tabController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: null,
        automaticallyImplyLeading : false,
        title: Text(widget.title),
      ),
      body:new TabBar(
          tabs: _tabList.map((value){
            return Container(
              child: Text(
                  value,
              ),
              height: 50,
              alignment:Alignment.center
            );
          }).toList(),
        controller: _tabController,
        isScrollable: true,//tab是否可滚动,
        indicatorWeight: 4,//指示器高度
        indicatorColor: Colors.black,
        indicatorSize: TabBarIndicatorSize.label,//和字体等宽,或者和tab等宽
        indicatorPadding: EdgeInsets.only(top: 50),//下划线间距
        indicator: new UnderlineTabIndicator(
            borderSide:new BorderSide(width: 4.0, color: Colors.blue),
            insets:EdgeInsets.zero
        ),//优先 indicatorWeight,indicatorColor和indicatorPadding
        //labelPadding: EdgeInsets.only(top: 50),//字体间距
        labelStyle:TextStyle(
         // color: Colors.black,//这个貌似无效
          fontSize: 18,
          fontWeight: FontWeight.bold
        ),
        labelColor: Colors.black,
        unselectedLabelStyle: TextStyle(
          fontSize: 16,
        ),
        unselectedLabelColor: Colors.grey,
        onTap: (pos){//点击事件
          print("type====$pos");
        },
      ),
    );
  }
}

TabBar 必须配置 TabController ,配置方式具体如上面,另外其他一些属性都是指示器的样式设置,选中字体的样式,和未选中的字体样式。

最后效果图为

效果图.png

相关文章

网友评论

      本文标题:Flutter 之 TabBar 控件

      本文链接:https://www.haomeiwen.com/subject/rmtlectx.html