如何防止一个方向滚动?

时间:2018-06-21 15:29:45

标签: flutter

我有一个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(),
  ...
);

但是它似乎只是禁用了拖动动作的视觉部分,因为选项卡在拖动结束时仍会更改。我该怎么办?

1 个答案:

答案 0 :(得分:1)

TabBarView上定义TabController,然后使用控制器的addListener方法检查控制器的indexpreviousIndexindexIsChanging属性

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(),
      ),
    );
  }
}