Flutter 滚动监听及实战appBar滚动渐变

本文详细介绍了Flutter中实现滚动监听的两种方式:ScrollController和NotificationListener。通过ScrollController,可以控制滚动、获取滚动位置,适用于监听整个Widget树。而NotificationListener则可以在任意位置监听滚动事件,提供更灵活的控制。文中通过实例展示了如何实现AppBar滚动渐变效果,以及如何在NotificationListener中监听滚动偏移量。
摘要由CSDN通过智能技术生成

介绍

在 Flutter 中滚动监听一般可以采用两种方式来实现,分别是 ScrollControllerNotificationListener 这两种方式。

ScrollController介绍

ScrollController

介绍一下ScrollController常用的属性和方法:

  • offset:可滚动组件当前的滚动位置。
  • jumpTo(double offset) 跳转到指定位置,offset 为滚动偏移量。
  • animateTo(double offset,@required Duration duration,@required Curve curve)jumpTo(double offset) 一样,不同的是 animateTo 跳转时会执行一个动画,需要传入执行动画需要的时间和动画曲线。

ScrollPosition

ScrollPosition是用来保存可滚动组件的滚动位置的。一个 ScrollController 对象可能会被多个可滚动的组件使用,

ScrollController 会为每一个滚动组件创建一个 ScrollPosition 对象来存储位置信息。ScrollPosition 中存储的是在 ScrollController 的 positions 属性里面,他是一个 List<ScrollPosition> 数组,在 ScrollController 中真正保存位置信息的就是 ScrollPosition,而 offset 只是一个便捷使用的属性。查看源码中可以发现 offset 获取就是从 ScrollPosition 中获取的。

  /// Returns the attached [ScrollPosition], from which the actual scroll offset
  /// of the [ScrollView] can be obtained.
  /// Calling this is only valid when only a single position is attached.
  ScrollPosition get position {
    assert(_positions.isNotEmpty, 'ScrollController not attached to any scroll views.');
    assert(_positions.length == 1, 'ScrollController attached to multiple scroll views.');
    return _positions.single;
  } 

  /// The current scroll offset of the scrollable widget.
  /// Requires the controller to be controlling exactly one scrollable widget.
  double get offset => position.pixels;

一个 ScrollController 虽然可以对应多个可滚动组件,但是读取滚动位置 offset,则需要一对一读取。在一对多的情况下,我们可以使用其他方法来实现读取滚动位置。假设现在一个 ScrollController 对应了两个可以滚动的组件,那么可以通过 position.elementAt(index) 来获取 ScrollPosition,从而获得 offset

controller.positions.elementAt(0).pixels
controller.positions.elementAt(1).pixels

ScrollPosition的方法

ScrollPosition 有两个常用方法:分别是 animateTo()

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值