Sub topic 13
Platform-appropriate scrolling
This chapter assumes you can build a ListView, wrap an app in MaterialApp or CupertinoApp, and read Theme.of(context).platform as covered in the earlier chapters. Scrolling is the part of platform adaptation that most users feel but rarely notice. Flutter handles most of it for you. The rest comes down to knowing which object controls it and when to override it.
What differs between platforms
An iOS list and an Android list differ in several ways when you drag past the end.
| Behavior | iOS and macOS | Android | Desktop (Windows, Linux) |
|---|---|---|---|
| Overscroll | Content bounces past the edge and springs back | Content stops at the edge, with a glow or stretch effect | Content stops at the edge |
| Fling deceleration | Slower, longer glide | Faster stop | Faster stop |
| Scrollbar | Appears only while scrolling | None by default | Always-available bar you can drag |
| Pull to refresh | Spinner revealed above the list | Circular indicator pulled down | Rarely used |
| Mouse drag to scroll | Not applicable | Not applicable | Off by default |
Flutter encodes these differences in two kinds of objects:
ScrollPhysicsdecides how a scroll position responds to drags, flings, and edges.ScrollBehavioris the app-wide policy. It chooses default physics, wraps scrollables in a scrollbar, adds an overscroll indicator, and lists which input devices may drag.
How a list picks its physics
A scrollable asks the nearest ScrollConfiguration for a ScrollBehavior. The behavior returns default physics for the current platform. If you pass physics: to the widget, that value is applied on top of the default.
The built-in defaults of ScrollBehavior, and of MaterialScrollBehavior which MaterialApp installs, are:
- iOS and macOS:
BouncingScrollPhysics. - Android, Fuchsia, Windows and Linux:
ClampingScrollPhysics. - Scrollbars:
MaterialScrollBehavioradds aScrollbarto vertical scrollables on desktop only. - Android overscroll:
MaterialScrollBehaviordraws a stretch effect whenuseMaterial3is true, and a glow otherwise.
CupertinoApp installs its own CupertinoScrollBehavior. It prefers bouncing physics even on non-Apple platforms, so a CupertinoApp on Android bounces. Check the API docs for your Flutter version if this matters to you.
The platform comes from getPlatform(context). In MaterialScrollBehavior it reads Theme.of(context).platform. That is the same value you use for adaptive widgets, so a platform override in a theme or test changes scrolling too.
Overriding physics on one list
Set physics on a single scrollable when one screen needs different behavior from the rest of the app. The value is chained onto the platform default.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: PhysicsDemo()));
class PhysicsDemo extends StatelessWidget {
const PhysicsDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Physics')),
body: ListView.builder(
// Short content still scrolls, and it bounces on every platform.
physics: const BouncingScrollPhysics(
parent: AlwaysScrollableScrollPhysics(),
),
itemCount: 5,
itemBuilder: (context, i) => ListTile(title: Text('Row $i')),
),
);
}
}AlwaysScrollableScrollPhysics lets the list be dragged even when its content fits the screen. You need it for pull-to-refresh on short lists. Without it, a list with few rows cannot be pulled, so the refresh gesture never starts.
Use NeverScrollableScrollPhysics when a parent controls the scroll position, for example a list nested inside a PageView.
Setting one policy for the whole app
To change behavior everywhere, subclass ScrollBehavior and pass it to the app's scrollBehavior argument. Extending MaterialScrollBehavior keeps the platform defaults and lets you change only what you need.
The most common reason is mouse dragging. By default, dragDevices excludes PointerDeviceKind.mouse. On desktop and web a user can scroll with the wheel and the scrollbar, but cannot click and drag the list. This also affects PageView and carousels on web, where it looks like a bug.
import 'dart:ui' show PointerDeviceKind;
import 'package:flutter/material.dart';
class AppScrollBehavior extends MaterialScrollBehavior {
const AppScrollBehavior();
@override
Set<PointerDeviceKind> get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
PointerDeviceKind.stylus,
PointerDeviceKind.trackpad,
};
}
void main() => runApp(
MaterialApp(
scrollBehavior: const AppScrollBehavior(),
home: Scaffold(
body: PageView(
children: const [
Center(child: Text('Page 1')),
Center(child: Text('Page 2')),
Center(child: Text('Page 3')),
],
),
),
),
);You can also override getScrollPhysics, buildScrollbar and buildOverscrollIndicator. For example, returning the child from buildScrollbar removes desktop scrollbars from the whole app.
To scope a policy to a subtree, wrap it in a ScrollConfiguration:
import 'package:flutter/material.dart';
class NoGlowSection extends StatelessWidget {
const NoGlowSection({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(
overscroll: false,
scrollbars: false,
),
child: child,
);
}
}copyWith keeps the inherited platform logic and turns off two decorations. This is safer than building a new behavior from scratch.
Scrollbars
A scrollbar is one of the most visible platform differences, and there are three ways to get one:
- Automatic:
MaterialScrollBehavioradds aScrollbaron desktop. You write nothing. CupertinoScrollbar: a thin bar that fades in during scrolling, in iOS style. It can also be made draggable withthumbVisibilityandthickness.Scrollbar.adaptive: picksCupertinoScrollbaron iOS and macOS and the MaterialScrollbarelsewhere.
Wrap the scrollable directly and share a controller if you create the scrollbar yourself:
import 'package:flutter/material.dart';
class AdaptiveScrollbarList extends StatefulWidget {
const AdaptiveScrollbarList({super.key});
@override
State<AdaptiveScrollbarList> createState() => _AdaptiveScrollbarListState();
}
class _AdaptiveScrollbarListState extends State<AdaptiveScrollbarList> {
final _controller = ScrollController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scrollbar.adaptive(
controller: _controller,
child: ListView.builder(
controller: _controller,
itemCount: 100,
itemBuilder: (context, i) => ListTile(title: Text('Item $i')),
),
);
}
}Without a shared controller, a Scrollbar falls back to the PrimaryScrollController. That works only if the list is the primary scrollable of the screen. It can fail silently with nested lists, and the usual symptom is a thumb that never appears.
Pull to refresh
Both platform conventions exist as separate widgets:
RefreshIndicator: the Material drag-down circle.RefreshIndicator.adaptiveswaps its spinner for aCupertinoActivityIndicatoron iOS and macOS. The gesture mechanics stay the same.CupertinoSliverRefreshControl: a sliver that sits at the top of aCustomScrollView. It uses bouncing overscroll to reveal the spinner above the content, as native iOS apps do.
The Cupertino sliver only works with bouncing physics. On a clamping list, nothing overscrolls, so nothing is revealed. If you place it in an app that also runs on Android, set BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()) on that CustomScrollView, or choose between the two widgets with the platform check from the earlier chapter.
Testing scroll behavior
Because MaterialScrollBehavior reads the theme platform, you can verify the defaults without a device. Read the physics from the ScrollableState:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Widget _app(TargetPlatform platform) => MaterialApp(
theme: ThemeData(platform: platform),
home: Scaffold(
body: ListView(
children: [for (var i = 0; i < 50; i++) Text('Row $i')],
),
),
);
void main() {
testWidgets('iOS lists bounce', (tester) async {
await tester.pumpWidget(_app(TargetPlatform.iOS));
final state = tester.state<ScrollableState>(find.byType(Scrollable));
expect(state.position.physics, isA<BouncingScrollPhysics>());
});
testWidgets('Android lists clamp', (tester) async {
await tester.pumpWidget(_app(TargetPlatform.android));
final state = tester.state<ScrollableState>(find.byType(Scrollable));
expect(state.position.physics, isA<ClampingScrollPhysics>());
});
}If you supply a custom ScrollBehavior, add a test that asserts your dragDevices or physics override, since nothing else will notice a regression.
Common errors
- Refresh never triggers on a short list. The content fits the viewport, so the list cannot be dragged. Add
AlwaysScrollableScrollPhysics. - Replacing instead of chaining physics. Passing
physics: ClampingScrollPhysics()discards the platform default. If you want to modify the default rather than replace it, useparent:orScrollConfiguration.copyWith. - Mouse drag does nothing on web. Add
PointerDeviceKind.mousetodragDevices. - Scrollbar thumb missing. Give the
Scrollbarand the scrollable the sameScrollController. - Testing with
dart:iochecks. Platform checks inPlatform.isIOSignore the theme override, so tests cannot reach those branches.
Exercise
Your Flutter web app has a horizontal PageView carousel. It scrolls with the trackpad on a laptop, but a colleague using a desktop mouse cannot click and drag between pages. Which object do you change, and what do you add to it?
Show answer
Change the app's ScrollBehavior. Subclass MaterialScrollBehavior, override dragDevices to include PointerDeviceKind.mouse (with the default touch, stylus and trackpad kinds), and pass an instance to MaterialApp's scrollBehavior argument. The default dragDevices excludes mouse, so PageView ignores mouse drags until you add it.
Exercise
A list with three rows sits under a RefreshIndicator, and pulling down on iOS does nothing. What is the cause, and what is the fix?
Show answer
Three rows do not fill the viewport, so the list has no scroll extent and cannot be dragged, which means no overscroll notification reaches the RefreshIndicator. Set physics to AlwaysScrollableScrollPhysics, for example BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), so the list accepts drags even when it fits.