flutter PageView已经在第一页或最后一页且尝试左右滑动时,执行需要的操作

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 执行后续操作
    }
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值