tezvyn:

Flutter's Physics Simulations: The Simulation Class

AI-drafted, machine-checkedSource: api.flutter.devadvanced

Flutter's `Simulation` class is the engine for physics-based animations, modeling a 1D object's position and velocity over time. It powers realistic scrolling, springs, and gravity effects.

WHY IT EXISTS To move beyond static, pre-defined animation curves and enable animations that feel natural and respond dynamically to user input or changing conditions. The Simulation class allows developers to describe motion in terms of physical forces like friction or gravity, rather than fixed start and end points.

THE MENTAL MODEL A Simulation is a tiny, one-dimensional physics engine. You give it a time t, and it tells you exactly where an object is (x(t)) and how fast it's moving (dx(t)). It's the blueprint for behaviors like a ball rolling to a stop (FrictionSimulation) or a spring oscillating (SpringSimulation).

HOW IT WORKS Simulation is an abstract class; you use a concrete implementation like SpringSimulation or create your own. The core contract is providing three methods: x(time) for position, dx(time) for velocity, and isDone(time) to check if it has settled. An AnimationController typically provides the elapsed time on each frame, and the simulation calculates the result. The system is unit-agnostic; you must establish a convention for distance and velocity (e.g., pixels and pixels-per-second) and use it consistently. The tolerance property defines how close to rest the object must be for isDone to return true.

WHEN TO USE IT Use it when you need motion that feels physically plausible and responsive. This is ideal for scroll physics (like BouncingScrollSimulation), creating springy UI elements that overshoot and settle, or animating an object under the influence of gravity. It's the go-to for animations that are not simple A-to-B transitions.

WHEN NOT TO USE IT For simple, fixed-duration, A-to-B animations with a predictable path, a standard Tween with a Curve is simpler and more performant. If your animation must follow a precise, non-physical timing, a Simulation adds unnecessary complexity.

ONE CANONICAL EXAMPLE Flinging a scrollable list. A FrictionSimulation is initiated with the fling's velocity. On each frame, the animation system asks the simulation for the new scroll offset based on elapsed time and a friction coefficient, creating a realistic slowdown. If you overscroll on iOS, a BouncingScrollSimulation might take over to create the rubber-band effect. This is all powered by the Simulation class via ScrollPhysics.

Read the original → api.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.