TabBar

TabBar

在页面上渲染 TabBar 组件,通常配合 Scaffold 组件的 bottomNavigationBar 属性一起使用,用来渲染底部的 TabBar 效果。

注意:

  • TabBar 最好和有状态页面配合使用

  • TabBar 必须指定 TabController 控制器,用来控制 TabBar 的切换

  • 如若不指定 TabController 控制器,也可以使用 DefaultTabController 组件,把 TabBar 组件包裹起来,同时提供需要切换的页面个数即可,代码示例如下:

DefaultTabController(
  // 指定需要切换的页面个数
  length: tablist.length,
  child: Scaffold(
    appBar: AppBar(),
    // 被 tabbar 控制切换的页面
    body: TabBarView(),
    // 指定 tab 项
    bottomNavigationBar: TabBar(
      tabs: tablist
    )
  ),
)
  • TabController 必须用在拥有 TickerProviderStateMixin 或 SingleTickerProviderStateMixin 特征的类中,因此,必须让 TabController 所在的类实现此特征,代码示例如下:
class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin { }

实现步骤:

  • 创建对应的 Tab 项:
List<Widget> tablist = <Widget>[
  Tab(
    text: '正在热映',
    icon: Icon(Icons.movie),
  ),
  Tab(
    text: '即将上映',
    icon: Icon(Icons.movie_filter),
  ),
  Tab(
    text: 'Top250',
    icon: Icon(Icons.local_movies),
  ),
];
  • 创建 TabController 对象:
TabController tabCtrl;
  • 在 initState 生命周期函数中,初始化 tabCtrl 对象:
@override
void initState() {
  super.initState();
  tabCtrl = TabController(vsync: this, length: tablist.length);
}
  • 为 Scaffold 添加 bottomNavigationBar 选项如下:
bottomNavigationBar: Container(
  // 设置 tabbar 的背景色
  decoration: BoxDecoration(color: Colors.black),
  // 设置 tabbar 的高度
  height: 50,
  // 指定 tabbar 组件
  child: TabBar(
    // 指定 tabbar 的控制器,必须提供控制器,否则 tabbar 不能正常工作
    controller: tabCtrl,
    // 设置 tabbar 中文本的样式,注意,height 属性很重要,必须设置为 0,否则文本和图标之间的距离太大,不美观
    labelStyle: TextStyle(height: 0, fontSize: 10),
    // 设置指示器的颜色
    indicatorColor: Colors.red,
    // 指定当前 tabbar 总共有几个按钮
    tabs: tablist,
  ),
)