Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to controll the velocity of a ListView builder?

Tags:

flutter

dart

I have a ListView.builder and I would like to control the speed of the scroll in the ListView but I couldn't find a solution for this besides extending the Simulation where I then override the velocity and then extend the ScrollingPhysics class and provide the velocity from there. But I couldn't figure out how I should do it.

Do you have any other solutions or an example for how to do this?

like image 833
P.Lorand Avatar asked Jan 28 '23 19:01

P.Lorand


1 Answers

If you need android-like scroll behavior take a look at ClampingScrollSimulation's constructor parameter friction. For ScrollPhysics, it is a coefficient of scrolling deceleration. The more friction is, the sooner scroll view stops scrolling.

You can control friction in custom scroll physics class:

class CustomScrollPhysics extends ScrollPhysics {
  const CustomScrollPhysics({ScrollPhysics parent}) : super(parent: parent);

  @override
  CustomScrollPhysics applyTo(ScrollPhysics ancestor) {
    return CustomScrollPhysics(parent: buildParent(ancestor));
  }

  ...

  @override
  Simulation createBallisticSimulation(
      ScrollMetrics position, double velocity) {
    final tolerance = this.tolerance;
    if ((velocity.abs() < tolerance.velocity) ||
        (velocity > 0.0 && position.pixels >= position.maxScrollExtent) ||
        (velocity < 0.0 && position.pixels <= position.minScrollExtent)) {
      return null;
    }
    return ClampingScrollSimulation(
      position: position.pixels,
      velocity: velocity,
      friction: 0.5,    // <--- HERE
      tolerance: tolerance,
    );
  }
}

And use it for ScrollView subclass widget:

ListView.builder(
  physics: CustomScrollPhysics(), 
  itemBuilder: (context, index) {
    ...
}) 
like image 171
Mol0ko Avatar answered Feb 01 '23 18:02

Mol0ko