Designing Delightful Scrolling in Flutter with Custom ScrollPhysics

Master Flutter custom scroll physics: compose built-ins, craft elastic overscroll, add snapping, and configure app-wide behavior with ScrollBehavior.

ASOasis
7 min read
Designing Delightful Scrolling in Flutter with Custom ScrollPhysics

Image used for representation purposes only.

Why custom scroll physics matter in Flutter

Great scrolling is invisible until it isn’t. Micro-interactions—how a list resists when you pull past the edge, how it decelerates after a fling, or how it snaps to meaningful positions—communicate quality and intent. Flutter exposes these behaviors through ScrollPhysics, letting you pick a built-in model or craft one that matches your product’s personality.

This article explains how Flutter’s scroll physics work, how to compose existing physics, and how to build your own—from a subtle rubber-band overscroll to a snappy, item-aligned list. We’ll also cover app-wide configuration, testing, and performance tips.

Scroll physics 101

At a glance:

  • Scrollable widgets (ListView, GridView, SingleChildScrollView, PageView, etc.) accept a physics parameter.
  • A ScrollPhysics describes how user drag, overscroll, and inertial (ballistic) motion should behave.
  • Key hooks you can override when creating custom physics:
    • applyPhysicsToUserOffset(ScrollMetrics position, double offset): transforms the finger drag delta into a scroll delta. Useful for friction/resistance.
    • applyBoundaryConditions(ScrollMetrics position, double value): clamps or limits motion when attempting to cross boundaries.
    • createBallisticSimulation(ScrollMetrics position, double velocity): returns a Simulation (e.g., spring or clamping) that runs after the finger lifts.
  • ScrollMetrics tells you where you are (pixels), the bounds (minScrollExtent/maxScrollExtent), and viewport size (viewportDimension).

Built-in physics (and when to use them)

  • ClampingScrollPhysics (Android-like): No elastic bounce at the edge. Good for platform-consistent behavior on Android/desktop.
  • BouncingScrollPhysics (iOS-like): Elastic bounce and resistance near edges. Great for content-centric UIs on Apple platforms.
  • AlwaysScrollableScrollPhysics / NeverScrollableScrollPhysics: Force-enable or disable user scrolling.
  • PageScrollPhysics: Page-like snapping with a PageView.
  • RangeMaintainingScrollPhysics: Helps keep content in view when the scroll extent changes.

Tip: You can compose physics by specifying a parent. For example, a bouncing list that is always scrollable:

ListView(
  physics: const BouncingScrollPhysics(
    parent: AlwaysScrollableScrollPhysics(),
  ),
)

When to craft your own physics

  • You want a distinctive brand feel: subtle resistance, lower/higher friction, or different edge behavior.
  • You need domain-specific snapping (e.g., to item rows of a fixed height, to calendar weeks, or to chapter markers).
  • You want to remove glow, emulate another platform, or unify behavior across platforms.

Example 1: A subtle rubber-band overscroll

Let’s create physics that feel slightly elastic near the edges, then spring back smoothly when released.

import 'dart:math' as math;
import 'package:flutter/physics.dart';
import 'package:flutter/widgets.dart';

class RubberBandPhysics extends ScrollPhysics {
  const RubberBandPhysics({super.parent, this.stiffness = 0.5, this.spring = const SpringDescription(mass: 0.5, stiffness: 100.0, damping: 15.0)});

  /// Higher values increase resistance more quickly near the edge.
  final double stiffness;

  /// Spring used when snapping back from overscroll.
  final SpringDescription spring;

  @override
  RubberBandPhysics applyTo(ScrollPhysics? ancestor) {
    return RubberBandPhysics(
      parent: buildParent(ancestor),
      stiffness: stiffness,
      spring: spring,
    );
  }

  @override
  double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
    // Inside bounds, pass through unmodified.
    final bool inRange = position.pixels >= position.minScrollExtent &&
        position.pixels <= position.maxScrollExtent;
    if (inRange) return offset;

    // Outside bounds: apply non-linear resistance that increases with overscroll.
    final double overscrollPastStart = math.max(position.minScrollExtent - position.pixels, 0.0);
    final double overscrollPastEnd = math.max(position.pixels - position.maxScrollExtent, 0.0);
    final double overscroll = math.max(overscrollPastStart, overscrollPastEnd);

    final double fraction = (overscroll / position.viewportDimension).clamp(0.0, 1.0);
    // Convert fraction into a friction factor in [0, 1).
    final double friction = 1.0 - (1.0 / ((fraction * stiffness) + 1.0));

    return offset * (1.0 - friction);
  }

  @override
  Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
    // If out of range, spring back to the nearest boundary.
    final bool outOfRange = position.pixels < position.minScrollExtent ||
        position.pixels > position.maxScrollExtent;
    if (outOfRange) {
      final double target = position.pixels.clamp(
        position.minScrollExtent,
        position.maxScrollExtent,
      );
      return ScrollSpringSimulation(
        spring,
        position.pixels,
        target,
        velocity,
        tolerance: tolerance,
      );
    }

    // Otherwise, delegate to parent (platform default deceleration).
    return super.createBallisticSimulation(position, velocity);
  }
}

Usage:

ListView.builder(
  physics: const RubberBandPhysics(
    parent: ClampingScrollPhysics(), // preserve Android-like deceleration inside range
    stiffness: 0.6,
  ),
  itemCount: 100,
  itemBuilder: (context, i) => ListTile(title: Text('Item $i')),
)

What you get: standard clamping inside bounds, gentle resistance when dragging past the edges, and a spring-back when you release.

Example 2: Snap a list to fixed row heights

If your list has uniform item heights (e.g., 72 px), snapping to the closest row on lift-off creates a crisp, paginated feel without a PageView.

import 'package:flutter/physics.dart';
import 'package:flutter/widgets.dart';

class SnapToItemPhysics extends ScrollPhysics {
  const SnapToItemPhysics({
    super.parent,
    required this.itemExtent,
    this.velocityThreshold = 300.0,
    this.spring = const SpringDescription(mass: 0.5, stiffness: 120.0, damping: 14.0),
  });

  final double itemExtent;
  final double velocityThreshold;
  final SpringDescription spring;

  @override
  SnapToItemPhysics applyTo(ScrollPhysics? ancestor) {
    return SnapToItemPhysics(
      parent: buildParent(ancestor),
      itemExtent: itemExtent,
      velocityThreshold: velocityThreshold,
      spring: spring,
    );
  }

  double _targetPixels(ScrollMetrics position, double velocity) {
    final double page = position.pixels / itemExtent;
    double targetPage;

    if (velocity.abs() < velocityThreshold) {
      // Low velocity: round to the nearest item.
      targetPage = page.roundToDouble();
    } else {
      // High velocity: advance one item in fling direction.
      targetPage = velocity > 0 ? page.floorToDouble() + 1.0 : page.ceilToDouble() - 1.0;
    }

    final double target = targetPage * itemExtent;
    return target.clamp(position.minScrollExtent, position.maxScrollExtent);
  }

  @override
  Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
    final double target = _targetPixels(position, velocity);
    if ((target - position.pixels).abs() < tolerance.distance) {
      return null; // we're already close enough
    }
    return ScrollSpringSimulation(
      spring,
      position.pixels,
      target,
      velocity,
      tolerance: tolerance,
    );
  }
}

Usage:

ListView.builder(
  physics: const SnapToItemPhysics(itemExtent: 72.0),
  itemExtent: 72.0, // required for consistent snapping
  itemCount: 200,
  itemBuilder: (context, i) => ListTile(title: Text('Row $i')),
)

Notes:

  • Works best when every item has the same height (itemExtent or prototypeItem).
  • For mixed heights, consider snapping to semantic anchors (headers) you compute from layout, or use PageView with PageScrollPhysics.

App-wide behavior with ScrollBehavior and ScrollConfiguration

You can set defaults for the entire app by providing a custom ScrollBehavior. This is the recommended way to:

  • Unify physics across platforms.
  • Remove the Android overscroll glow.
  • Customize drag devices and scrollbar presence (if needed).
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class AppScrollBehavior extends MaterialScrollBehavior {
  const AppScrollBehavior();

  @override
  ScrollPhysics getScrollPhysics(BuildContext context) {
    // Example: iOS/macOS bounce, others clamp.
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        return const BouncingScrollPhysics();
      default:
        return const ClampingScrollPhysics();
    }
  }

  @override
  Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
    // Remove glow entirely; return the child untouched.
    return child;
  }
}

MaterialApp(
  scrollBehavior: const AppScrollBehavior(),
  home: const MyHomePage(),
);

If you only want to affect a subtree, wrap it with ScrollConfiguration(behavior: const AppScrollBehavior(), child: ...).

Composition patterns and gotchas

  • Compose, don’t rewrite: Many customizations can be achieved by layering parents, e.g., BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()).
  • Nested scrollables: Parent and child physics can both apply. If a child scrollable is inside another, ensure only one is intended to handle the gesture (e.g., disable the child or use NeverScrollableScrollPhysics for the child when appropriate).
  • PageView + custom physics: Favor PageScrollPhysics as a parent to preserve expected paging. For example, SnapToItemPhysics(parent: const PageScrollPhysics(), itemExtent: 72) if used within a PageView-like layout.
  • Dynamic extents: If your content size changes during a drag, be mindful of spring-back targets. RangeMaintainingScrollPhysics can help minimize content jumps.

Testing your physics

Write widget tests to validate how your physics feel and behave:

import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('List snaps to 72px increments', (tester) async {
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: ListView.builder(
          physics: const SnapToItemPhysics(itemExtent: 72.0),
          itemExtent: 72.0,
          itemCount: 50,
          itemBuilder: (context, i) => Text('Row $i'),
        ),
      ),
    );

    // Fling roughly one and a half items.
    await tester.fling(find.byType(ListView), const Offset(0, -110), 600);
    await tester.pumpAndSettle();

    final ScrollableState state = tester.state(find.byType(Scrollable));
    final position = state.position;

    // Expect we're close to an integer multiple of 72.
    expect((position.pixels / 72.0).remainder(1.0), moreOrLessEquals(0.0, epsilon: 0.1));
  });
}

What to test:

  • Spring-back at edges returns to exactly minScrollExtent/maxScrollExtent.
  • Snapping lands on predictable anchors given different velocities.
  • Performance: long lists remain smooth during drag and fling.

Performance and UX guidelines

  • Keep math light in applyPhysicsToUserOffset: it’s called every frame during a drag.
  • Reuse immutable objects: predefine SpringDescriptions; avoid allocations inside hot paths.
  • Respect platform expectations unless you have a strong reason to differ. Users notice when scrolling feels “off.”
  • Provide affordances with physics: subtle resistance can hint that no more content exists, while a bounce suggests “elastic” content.
  • Don’t fight the user: overly aggressive snapping or heavy resistance frustrates. Make thresholds and stiffness configurable.

Troubleshooting

  • “My custom physics don’t seem to apply”:
    • Verify no parent ScrollConfiguration overrides them.
    • Check for a nested scrollable that’s consuming gestures first.
    • Ensure you passed the physics to the correct widget (e.g., the ListView, not a parent container).
  • “Overscroll glow still appears on Android”:
    • Provide a ScrollBehavior that returns the child directly in buildOverscrollIndicator.
  • “Snapping is jittery”:
    • Make sure the target anchor calculation is stable and clamped to bounds.
    • Avoid re-computing anchors with layout-dependent values during the animation.

Wrap-up

Flutter’s ScrollPhysics API lets you dial in exactly how your UI should feel. Start by composing the built-in physics for quick wins. When you need something unique, implement a small custom class: transform user drag deltas with applyPhysicsToUserOffset, and define a clean, predictable createBallisticSimulation. With careful testing and lightweight math, you can deliver delightful, brand-aligned scrolling that users feel—often without noticing why it feels so good.

Related Posts