flutter PageView與TabBarView嵌套滾動(dòng)的實(shí)現(xiàn)

參考:github項(xiàng)目地址

我這邊是的App的首頁(yè)是PageView里加了5個(gè)頁(yè)面,其中有一個(gè)頁(yè)面是包含了TabBarView。在滾動(dòng)的過(guò)程中,當(dāng)TabBarView滾動(dòng)到最后一頁(yè)或者第一頁(yè)面的時(shí)候,不能和PageView進(jìn)行聯(lián)動(dòng)。所以查詢了很多種方式,覺(jué)的上面作者實(shí)現(xiàn)的方式很不錯(cuò)。代碼量不多。

1.創(chuàng)建一個(gè)PageViewScrollUtils助手類,當(dāng)監(jiān)聽(tīng)的需要的時(shí)機(jī),進(jìn)行相應(yīng)的操作

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class PageViewScrollUtils {
  final PageController pageController;
  final TabController tabController;
  PageViewScrollUtils({required this.pageController, required this.tabController});

  Drag? _drag;

  bool handleNotification(ScrollNotification notification) {
    if (notification is UserScrollNotification) {
      if ((notification.direction == ScrollDirection.reverse && tabController.index == tabController.length - 1) || (notification.direction == ScrollDirection.forward && tabController.index ==  0)) {
        _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;
  }
}

2.在TabBarView所在的頁(yè)面實(shí)例化PageViewScrollUtils,實(shí)例化的時(shí)候需要TabBarView與PageView的controller

_pageViewScrollUtils = PageViewScrollUtils(pageController: widget.pageController,tabController: _tabController);

3.在TabBarView 外邊套一個(gè)NotificationListener,監(jiān)聽(tīng)TabBarView滾動(dòng),并使用PageViewScrollUtils進(jìn)行處理

NotificationListener<ScrollNotification>(
                    child: TabBarView(
                          physics: ClampingScrollPhysics(),
                          controller: _tabController,
                          children: [
                            LobbyLayout(),
                            LobbyLayout(),
                            LobbyLayout(),
                            LobbyLayout()
                          ]
                      ),
                      onNotification: _pageViewScrollUtils.handleNotification,
                    )

4.這樣就可以了。非常簡(jiǎn)單,代碼量也很少。

點(diǎn)擊下方贊賞,給作者一點(diǎn)鼓勵(lì)!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容