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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM