我這邊是的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ì)!