介绍
在 Flutter 中滚动监听一般可以采用两种方式来实现,分别是 ScrollController
和 NotificationListener
这两种方式。
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()