Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 73 ยท Animation and graphics

Implicit Animations

Animate Flutter UI with almost no code: AnimatedContainer, TweenAnimationBuilder, AnimatedSwitcher, curves and durations, and how the tween engine works inside.

Motion tells users what just happened: a card grows when selected, a banner fades in, a number slides to its new value. Flutter has two families of animation tools. Implicit animations are the easy one: you change a property, and the widget animates from the old value to the new one by itself. You write no controller and no dispose.

This lesson covers AnimatedContainer, the other Animated* widgets, TweenAnimationBuilder, AnimatedSwitcher, curves and durations, and a stand-in tween engine that shows what happens between two values. It builds on StatefulWidget and setState and Padding, SizedBox, Container and ConstrainedBox. When you need full control, continue to Explicit Animations and AnimationController.

Real vs stand-in. The Dart is real Flutter code, read-only here, because the site has no Flutter runtime. The live examples are JavaScript stand-ins: a tween engine that interpolates values over time using a fake clock, so the output is the same on every run.

How an implicit animation works

Change a value setState with a new size or color.
Widget notices The old and new values differ.
Tween runs Values blend over the duration.
Frames build Each frame draws a middle value.
1 / 2

AnimatedContainer

AnimatedContainer is a Container that animates whenever its properties change. You give it a duration, and optionally a curve:

DART
class SelectableCard extends StatefulWidget {
  const SelectableCard({super.key});

  @override
  State<SelectableCard> createState() => _SelectableCardState();
}

class _SelectableCardState extends State<SelectableCard> {
  bool _selected = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() => _selected = !_selected),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
        width: _selected ? 220 : 160,
        height: 100,
        padding: EdgeInsets.all(_selected ? 24 : 12),
        decoration: BoxDecoration(
          color: _selected ? Colors.indigo : Colors.grey.shade300,
          borderRadius: BorderRadius.circular(_selected ? 28 : 8),
        ),
        child: Text(
          'Tap me',
          style: TextStyle(color: _selected ? Colors.white : Colors.black87),
        ),
      ),
    );
  }
}

Width, padding, color and corner radius all change in one setState, and all of them animate at once. When build runs, AnimatedContainer compares the new values with the ones it showed last time. Where they differ, it starts a tween from the old value to the new one. It can animate width, height, padding, margin, alignment, decoration, transform and more.

A bug to avoid: AnimatedContainer animates between two values of the same kind. If one state uses color: and the other uses decoration:, Flutter throws an assertion, because a Container cannot have both. Put the color inside the BoxDecoration in both states.

The Animated family

Many widgets have an animated twin that follows the same pattern (a duration, a curve, and properties that animate when changed):

Widget What it animates
AnimatedOpacity opacity (fade)
AnimatedPadding padding
AnimatedAlign alignment
AnimatedPositioned left/top/right/bottom inside a Stack
AnimatedScale / AnimatedRotation / AnimatedSlide scale, turns, offset
AnimatedDefaultTextStyle text style (size, color, weight)
AnimatedCrossFade fades between two children
AnimatedSize the size of its child when that changes

Fading something in is a one-liner:

DART
AnimatedOpacity(
  opacity: _visible ? 1.0 : 0.0,
  duration: const Duration(milliseconds: 250),
  child: const Text('Saved!'),
)

An invisible AnimatedOpacity child still takes space and still receives taps. Wrap it in IgnorePointer, or use Visibility, if it must not be tappable. AnimatedPositioned only works as a direct child of a Stack (see Stack, Align and Positioned).

Curves and durations

The duration says how long the animation lasts; the curve says how the speed changes over that time. Curves map progress t from 0 to 1 onto another 0 to 1 value:

  • Curves.linear: constant speed (feels mechanical).
  • Curves.easeInOut: slow start, fast middle, slow end. A good default.
  • Curves.easeOut: fast start, gentle stop. Good for things entering the screen.
  • Curves.bounceOut, Curves.elasticOut: playful overshoot, use sparingly.
  • Cubic(0.2, 0.0, 0.0, 1.0): your own cubic Bรฉzier.

Typical durations: 150 to 250 ms for small changes, 300 to 400 ms for larger ones. Anything over about 500 ms makes an interface feel slow.

Stand-in: a tween engine

Under the hood an implicit animation is just math: value = begin + (end - begin) * curve(t), where t goes from 0 to 1. This stand-in uses a fake clock stepping 50 ms at a time so you can read the in-between values.

JS Interpolating width with different curves

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All three curves start at 160 and end at 220. easeIn stays close to the start for longer and rushes at the end, easeOut moves most of the distance early. The animated widget does the same thing, only once per real frame.

TweenAnimationBuilder

What if no ready-made Animated* widget fits? TweenAnimationBuilder animates any value you choose, and rebuilds a builder with the current value on each frame:

DART
TweenAnimationBuilder<double>(
  tween: Tween(begin: 0, end: _score.toDouble()),
  duration: const Duration(milliseconds: 600),
  curve: Curves.easeOut,
  builder: (context, value, child) {
    return Text(value.round().toString(), style: const TextStyle(fontSize: 48));
  },
)

When _score changes, the tween's end changes. The widget animates from wherever it currently is to the new end, so repeated changes never jump. Because it keeps begin from its first build only when no previous value exists, the first display animates from 0; to avoid that, set begin to the starting score too.

Other useful tweens: ColorTween for colors, Tween<Offset> for movement and Tween<double> driving Transform.rotate. Pass static parts through the child argument so they are not rebuilt every frame:

DART
TweenAnimationBuilder<double>(
  tween: Tween(begin: 0, end: _turns),
  duration: const Duration(seconds: 1),
  child: const Icon(Icons.refresh, size: 48),   // built once
  builder: (context, turns, child) {
    return Transform.rotate(angle: turns * 2 * pi, child: child);
  },
)
JS Retargeting a running tween

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The value is 75 at the moment of retargeting and the new tween begins there, so the number glides toward 40 instead of snapping. That is why implicit animations feel smooth even when users tap quickly.

AnimatedSwitcher

When a child is replaced by a different widget, there is no number to tween. AnimatedSwitcher cross-fades between the old and new child. It needs to tell them apart, which is where keys come in (Keys and Widget Identity):

DART
AnimatedSwitcher(
  duration: const Duration(milliseconds: 250),
  transitionBuilder: (child, animation) =>
      ScaleTransition(scale: animation, child: child),
  child: Text(
    '$_count',
    key: ValueKey<int>(_count),     // a new key means "a new child"
    style: const TextStyle(fontSize: 40),
  ),
)

Without the ValueKey, the new Text has the same type and no key, so Flutter treats it as an update of the same widget and nothing animates. The default transition is a fade; transitionBuilder accepts any FadeTransition, ScaleTransition, SlideTransition, or a combination.

Shimmer, skeleton loaders and animated splash screens

Three "waiting" animations appear in nearly every app: a placeholder while content loads, a shimmer that shows life, and a splash screen while the app starts.

Skeleton loaders and shimmer

A skeleton is a gray outline of the content to come (a circle for the avatar, bars for text). It feels faster than a spinner because the layout does not jump when data arrives. A shimmer adds a highlight that sweeps across the skeleton. The shimmer package does this in one wrapper:

DART
Shimmer.fromColors(
  baseColor: Colors.grey.shade300,
  highlightColor: Colors.grey.shade100,
  child: Column(
    children: [
      for (var i = 0; i < 4; i++)
        ListTile(
          leading: const CircleAvatar(backgroundColor: Colors.white),
          title: Container(height: 12, color: Colors.white),
          subtitle: Container(height: 12, margin: const EdgeInsets.only(top: 8), color: Colors.white),
        ),
    ],
  ),
)

The children are drawn in plain white, and the package paints a moving gradient through them with a ShaderMask (see ClipRRect, ClipPath, ShaderMask and Opacity). You can build the effect yourself with an AnimationController that repeats and shifts the gradient's stops. Show the skeleton while a FutureBuilder is waiting, give the placeholder the same size as the real content, and use dark-theme colors when the theme is dark. Many shimmering rows cost repaint time, so keep the number modest.

JS A shimmer sweep as gradient stops

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Native splash screen

The first thing the user sees is the native splash, shown by the OS before Flutter has drawn anything. Flutter cannot animate it, but you can set its color and logo with the flutter_native_splash package: add a config block to pubspec.yaml, then run dart run flutter_native_splash:create.

YAML
flutter_native_splash:
  color: "#0B1220"
  image: assets/splash/logo.png
  android_12:
    color: "#0B1220"
    image: assets/splash/logo_android12.png

To keep it on screen while you load things (read settings, check login), preserve it and remove it when ready:

DART
Future<void> main() async {
  final binding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: binding);
  await initializeApp();                  // keep it short; users wait on this
  FlutterNativeSplash.remove();
  runApp(const MyApp());
}

Animated splash screen

For motion, show your own first Flutter screen that plays an animation, then navigates on. Combine a short minimum display time with the real start-up work so fast devices do not flash by:

DART
class _SplashState extends State<Splash> with SingleTickerProviderStateMixin {
  late final AnimationController _logo = AnimationController(vsync: this, duration: const Duration(milliseconds: 900))..forward();

  @override
  void initState() {
    super.initState();
    Future.wait([
      initializeApp(),
      Future<void>.delayed(const Duration(milliseconds: 1200)),   // minimum time on screen
    ]).then((_) {
      if (mounted) Navigator.of(context).pushReplacementNamed('/home');   // replace, so Back does not return here
    });
  }

  @override
  void dispose() { _logo.dispose(); super.dispose(); }

  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: FadeTransition(opacity: _logo, child: ScaleTransition(scale: _logo, child: const FlutterLogo(size: 96)))),
  );
}

Keep splash screens short: they delay the moment the app becomes useful, and a long forced animation annoys returning users. Never block on slow network calls here; show the home screen with a skeleton instead.

JS Minimum splash time plus real start-up work

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When implicit is not enough

Use explicit animations when the animation should loop, repeat, reverse on command, pause, be driven by a drag, or coordinate several parts with different timings. Also think about performance: animating width forces a re-layout every frame, while Transform-based widgets (AnimatedScale, AnimatedSlide, AnimatedRotation) only repaint. For heavy subtrees, prefer the transform widgets; see Performance and DevTools.

Finally, respect users who turn off motion: MediaQuery.of(context).disableAnimations tells you to use zero duration (see Accessibility and Internationalization).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do you need to write to make an AnimatedContainer animate a width change?

    Implicit animations need only a duration. When build gives them a new value, they tween to it themselves.
  2. 2. Why does AnimatedSwitcher need a key on the new child?

    AnimatedSwitcher compares child type and key. Two Text widgets without keys count as the same child.
  3. 3. A TweenAnimationBuilder's end value changes while it is animating. What happens?

    The animation is retargeted from its current value, so there is no visible jump.
  4. 4. Which curve starts slowly, speeds up and then slows down?

    easeInOut eases both at the start and at the end.
  5. 5. Which is cheaper to animate on complex content?

    Transforms only repaint, while size changes force layout for the subtree on every frame.

Summary

  • Implicit animations animate by themselves when a property changes: give a duration and a new value in setState.
  • Use the Animated* widgets for common properties, and TweenAnimationBuilder for anything else.
  • AnimatedSwitcher cross-fades replaced children and needs different keys.
  • A curve reshapes progress t; the value is begin + (end - begin) * curve(t).
  • Retargeting continues from the current value, so quick taps stay smooth.

Next: Explicit Animations and AnimationController