相比与 TabBar,使用 TabController 更有利于事件的监听,便于控制相关内容。
import 'package:flutter/material.dart';
class SettingsPage extends StatefulWidget {
SettingsPage({Key key}) : super(key: key);
@override
_SettingsPageState createState() => _SettingsPageState();
}
// 1 实现 SingleTickerProviderStateMixin
class _SettingsPageState extends State<SettingsPage>
with SingleTickerProviderStateMixin {
// 2 定义 TabController 变量
TabController _tabController;
// 3 覆盖重写 initState,实例化 _tabController
@override
void initState() {
// TODO: implement initState
super.initState();
_tabController = new TabController(length: 2, vsync: this);
_tabController.addListener(() {
print(_tabController.index);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('tabController'),
bottom: TabBar(
controller: _tabController, // 4 需要配置 controller!!!
// isScrollable: true,
tabs: <Widget>[
Tab(text: '推荐'),
Tab(text: '最新'),
],
),
),
body: TabBarView(
controller: _tabController, // 4 需要配置 controller!!!
children: <Widget>[
ListView(
children: <Widget>[
ListTile(
title: Text(
'diyigezuixin 推荐',
style: TextStyle(fontSize: 14.0),
),
),
ListTile(
title: Text('diyigezuixin 推荐'),
),
],
),
Container(
child: Text('zuixidddd'),
),
],
),
);
}
}

网友评论