1. 程式人生 > 實用技巧 >flutter實現PageView巢狀滾動

flutter實現PageView巢狀滾動

flutter實現PageView巢狀滾動

在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,
 )

效果如下所示:

視訊效果連結點選這裡

完整專案專案地址:https://github.com/yongfengnice/flutter_nest_page_view

有一個小小的瑕疵,就是滑回來的時候,要等內層的TabBarView動畫完成才能繼續,這樣可能出現快速滑回來時第一次無效的錯覺感,不過我覺得還可以接受。哪位大佬有好的解決方法可以優化一下。