1.自定义PageView的physics
import 'package:flutter/material.dart';
/*
* 自定义pageView的physics,PageView已经在第一页且尝试左右滑时回调出去
* */
class CustomPageScrollPhysics extends AlwaysScrollableScrollPhysics {
final VoidCallback? onLeftBoundaryReached;
final VoidCallback? onRightBoundaryReached;
const CustomPageScrollPhysics({
this.onLeftBoundaryReached,
this.onRightBoundaryReached,
ScrollPhysics? parent,
}) : super(parent: parent);
CustomPageScrollPhysics applyTo(ScrollPhysics? ancestor) {
return CustomPageScrollPhysics(
parent: buildParent(ancestor),
onLeftBoundaryReached: onLeftBoundaryReached,
onRightBoundaryReached: onRightBoundaryReached,
);
}
double applyBoundaryConditions(ScrollMetrics position, double value) {
final double delta = value - position.pixels; //<0:左滑;>0:右滑
//当在第一页且尝试左滑时
if (position.pixels <= position.minScrollExtent && value < position.pixels) {
onLeftBoundaryReached?.call(); // 触发回调
return delta;
}else if(position.pixels == position.maxScrollExtent && value > position.pixels){
//当在最后页面且尝试右滑
onRightBoundaryReached?.call(); //触发回调
return delta;
}
return super.applyBoundaryConditions(position, value);
}
}
2.调用
_bodyPageView(){
return PageView.builder(
allowImplicitScrolling: true, //true:缓存范围设置为当前页的前一页及后一页;false:缓存范围设置为0
controller: _pageController,
physics: CustomPageScrollPhysics(onLeftBoundaryReached: _handleLeftBoundaryReached,onRightBoundaryReached: _handleRightBoundaryReached),
onPageChanged: _onPageChanged,
itemCount: _tabValues.length,
itemBuilder: (_, index){
final e = _tabValues[index];
if (e['type'] == 0) {
return FollowShareList(key: ValueKey(e), catId: e['type']);
}
return UserShareList(
key: ValueKey(e), catId: e['id'], type: e['type'],shouldKeepAlive: false);
});
}
_handleLeftBoundaryReached() {
if (_pageController?.page?.round() == 0) {
esLoadingToast('抵达左边界-已经在第一页再次左滑');
//TODO 执行后续操作
}
}
_handleRightBoundaryReached() {
if (_pageController?.page?.round() == _tabValues.length -1) {
esLoadingToast('抵达右边界-已经在最后页再次右滑');
//TODO 执行后续操作
}
}
7391

被折叠的 条评论
为什么被折叠?



