flutter开发tab页面嵌套滚动的最简洁实现方式

flutter通过处理PageView滚动事件实现tab嵌套滚动

在app里实现内外层滚动是很常见的需求,比如app底部四个tab是可以滚动的,首页里的n多个tab又是可以滚动的,当首页里tab滚动到最后一个tab继续滑动时,希望滑动到底部下一个tab,但是flutter组件pageView嵌套时是不会自动处理的,所以需要我们自己处理滑动事件

  • 调试了大半天,感觉效果也差不多了,应该可以满足要求,代码很少,直接贴代码了
class PageViewScrollUtils {
  final PageController pageController;
  final TabController tabController;
  Drag _drag;

  PageViewScrollUtils(this.pageController, this.tabController);

  bool handleNotification(ScrollNotification notification) {
    if (notification is UserScrollNotification) {
      if (notification.direction == ScrollDirection.reverse && tabController.index == tabController.length - 1) {
        _drag = pageController.position.drag(DragStartDetails(), () {
          _drag = null;
        });
      }
    }
    if (notification is OverscrollNotification) {
      if (notification.dragDetails != null && _drag != null) {
        _drag.update(notification.dragDetails);
      }
    }
    if (notification is ScrollEndNotification) {
      if (notification.dragDetails != null && _drag != null) {
        _drag.end(notification.dragDetails);
      }
    }
    return true;
  }
}

以上一个工具类搞定,使用也非常简单,下面是使用demo:

 NotificationListener<ScrollNotification>(
  child: TabBarView(),
  onNotification: _pageViewScrollUtils.handleNotification,
 )

效果如下所示(视频转为gif后变慢的):

完整项目项目地址:https://github.com/yongfengnice/flutter_nest_page_view

原文地址:https://www.cnblogs.com/yongfengnice/p/14140103.html