animateTo method
void
animateTo(})
Animates the scroll position smoothly to value in pixels.
If duration is zero, animation will be ignored.
Example
final scrollController = ScrollController();
scrollController.animateTo(100.0);
Implementation
void animateTo(
double value, {
Duration duration = const Duration(milliseconds: 300),
Curves curve = Curves.easeInOut,
}) {
if (_attachedElement == null) return;
// jump immediately if duration is zero
if (duration == Duration.zero) {
jumpTo(value);
return;
}
// calculate starting offset and change
final startOffset = offset;
final change = value - startOffset;
// setup animation variables
final startTime = DateTime.now().millisecondsSinceEpoch;
final totalDurationMs = duration.inMilliseconds;
void step() {
if (_attachedElement == null) return;
// calculate animation progress
final elapsed = DateTime.now().millisecondsSinceEpoch - startTime;
final progress = (elapsed / totalDurationMs).clamp(
0.0,
1.0,
);
// calculate easing progress
final easedProgress = curve.build(progress);
// calculate current scroll position
final current = startOffset + change * easedProgress;
// update scroll position
if (direction == ScrollDirection.vertical) {
_attachedElement!.scrollTop = current;
} else {
_attachedElement!.scrollLeft = current;
}
// update scroll offset
_offset = current;
// notify listeners of scroll position changes
notifyListeners();
// continue animation if not done
if (progress < 1.0) onComponentRendered(step);
}
// start animation
step();
}