我有一个TabBarView
,我只想在一个方向上滚动即可。到目前为止,这是我尝试过的:
class NoForwardNavScrollPhysics extends ClampingScrollPhysics {
const NoForwardNavScrollPhysics({ ScrollPhysics parent }) : super(parent: parent);
@override
NoForwardNavScrollPhysics applyTo(ScrollPhysics ancestor) {
return new NoForwardNavScrollPhysics(parent: buildParent(ancestor));
}
@override
double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
return 0.0;
}
}
...
TabBarView(
physics: NoForwardNavScrollPhysics(),
...
);
但是它似乎只是禁用了拖动动作的视觉部分,因为选项卡在拖动结束时仍会更改。我该怎么办?
答案 0 :(得分:1)
在TabBarView
上定义TabController
,然后使用控制器的addListener
方法检查控制器的index
,previousIndex
和indexIsChanging
属性
class MyTabbedPage extends StatefulWidget {
const MyTabbedPage({ Key key }) : super(key: key);
@override
_MyTabbedPageState createState() => new _MyTabbedPageState();
}
class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {
final List<Tab> myTabs = <Tab>[
new Tab(text: 'LEFT'),
new Tab(text: 'RIGHT'),
];
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = new TabController(vsync: this, length: myTabs.length);
_tabController.addListener(_denyForwardsTab);
}
void _denyForwardsTab() {
if (_tabController.index == _tabController.previousIndex + 1) {
setState(() => _tabController.index = _tabController.previousIndex);
}
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
bottom: new TabBar(
controller: _tabController,
tabs: myTabs,
),
),
body: new TabBarView(
controller: _tabController,
children: myTabs.map((Tab tab) {
return new Center(child: new Text(tab.text));
}).toList(),
),
);
}
}