Flutter布局-Tab切换实现

TabBar

  • TabBarView成对使用

  • 使用TabController控制切换

  • indicator: BoxDecoration(),可以取消文字下面的横线

  • TabBarView中配置physics: NeverScrollableScrollPhysics(),可以禁止TabBarView左右滑动

  • TabBar常用属性:

名称 类型 说明
tabs List<Widget> 显示的标签内容,一般使用Tab对象,也可以是其他的Widget
controller TabController TabController对象
isScrollable bool 是否可滚动
indicatorColor Color 指示器颜色
indicatorWeight double 指示器高度
indicatorPadding EdgeInsetsGeometry 底部指示器的Padding
indicator Decoration 指示器decoration,例如边框等
indicatorSize TabBarIndicatorSize 指示器大小计算方式,TabBarIndicatorSize.label跟文字等宽,TabBarIndicatorSize.tab跟每个tab等宽
labelColor Color 选中label颜色
labelStyle TextStyle 选中labelStyle
labelPadding EdgeInsetsGeometry 每个label的 padding 值
unselectedLabelColor Color 未选中label颜色
unselectedLabelStyle TextStyle 未选中labelStyle

TabController

  • 有状态的组件,需要with SingleTickerProviderStateMixin

  • 初始化方法:this._controller = new TabController(length: 2, vsync: this);,这里用到了this,可以放在initState周期中

  • dispose周期中调用this._controller.dispose();方法销毁

import 'package:flutter/material.dart'; class FirstPage extends StatefulWidget { FirstPage({Key key}) : super(key: key); @override _FirstPageState createState() => _FirstPageState(); } class _FirstPageState extends State<FirstPage> with SingleTickerProviderStateMixin { TabController _controller; @override void initState() { super.initState(); this._controller = new TabController(length: 2, vsync: this); this._controller.addListener(() { print(this._controller.index); }); } @override void dispose() { this._controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('first page'), bottom: TabBar( indicatorSize: TabBarIndicatorSize.label, controller: this._controller, tabs: [ Tab(text: 'Tab1'), Tab(text: 'Tab2'), ] ), ), body: TabBarView( controller: this._controller, // 禁止TabBarView滑动 // physics: NeverScrollableScrollPhysics(), children: [ Container( child: Center( child: Text('Tab1 detail'), ), ), Container( child: Center( child: Text('Tab2 detail'), ), ) ] ), ); } }

创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: