Flutter: Animation System

Animation is the soul of UI — an interface without animation is like a slideshow, one with animation is like a movie.

📋 Prerequisites: You should already be familiar with

1. What You'll Learn


2. A Real Story of a Stiff Interface

(1) The Pain Point: State Changes Feel Like Slides

Bob's ShopApp product detail page jumps instantly when "Add to Cart" is tapped — the quantity goes from 0 to 1, the price jumps from $0 to $99.99, and the cart badge suddenly shows "3". Users think the app "froze" or "has a bug" — when in reality, it's just missing transition animations. 35% of users on the version without animations reported "UI lag".

(2) The Implicit Animation Solution

Flutter's implicit animation widgets only need a target value — the framework automatically generates the transition animation.

DART
import 'package:flutter/material.dart';

// Before: instant change (looks like a bug)
Text('\$$_total')

// After: smooth animation
AnimatedSwitcher(
  duration: const Duration(milliseconds: 300),
  child: Text('\$$_total', key: ValueKey(_total)),
)
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

(3) The Payoff: Improved Perceived Smoothness

After Bob added animations, "UI lag" reports dropped from 35% to 2%, and user session duration increased by 20%.


3. Animation System Overview

100%
graph TD
    A[Animation System] --> IA[Implicit Animation]
    A --> EA[Explicit Animation]
    IA --> AC[AnimatedContainer]
    IA --> AO[AnimatedOpacity]
    IA --> AS2[AnimatedSwitcher]
    EA --> ACTRL[AnimationController]
    ACTRL --> TW[Tween]
    ACTRL --> CURVE[CurvedAnimation]
    EA --> AB[AnimatedBuilder]
    EA --> HERO[Hero Transition]
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

(1) Implicit vs Explicit Animations

Dimension Implicit Animation Explicit Animation
Control Automatic (set target value) Manual (Controller-driven)
Complexity Low High
Flexibility Limited Full control
Loop/Reverse Not supported Supported
Use Case Simple transitions Complex custom animations

4. Implicit Animations

▶ Example

TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

: AnimatedContainer expand/collapse

DART
import 'package:flutter/material.dart';

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

  @override
  State<ExpandableCard> createState() => _ExpandableCardState();
}

class _ExpandableCardState extends State<ExpandableCard> {
  bool _expanded = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() => _expanded = !_expanded),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOutCubic,
        height: _expanded ? 200 : 80,
        padding: EdgeInsets.all(_expanded ? 16 : 8),
        decoration: BoxDecoration(
          color: _expanded ? Colors.blue[50] : Colors.white,
          borderRadius: BorderRadius.circular(_expanded ? 16 : 8),
          boxShadow: [BoxShadow(blurRadius: _expanded ? 12 : 4, color: Colors.black12)],
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('Pro Laptop', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
          if (_expanded) ...[
            const SizedBox(height: 12),
            const Text('Latest model with M3 chip. 16GB RAM, 512GB SSD.'),
            const SizedBox(height: 8),
            const Text('\$1,299.99', style: TextStyle(fontSize: 20, color: Colors.green)),
          ],
        ]),
      ),
    );
  }
}
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

▶ Example

TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

: AnimatedSwitcher number switching

DART
import 'package:flutter/material.dart';

class AnimatedPrice extends StatelessWidget {
  final double price;
  const AnimatedPrice({super.key, required this.price});

  @override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
      duration: const Duration(milliseconds: 300),
      transitionBuilder: (child, animation) => FadeTransition(opacity: animation, child: child),
      child: Text('\$${price.toStringAsFixed(2)}',
        key: ValueKey(price),
        style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.green),
      ),
    );
  }
}
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

▶ Example

TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

: AnimatedCrossFade view switching

DART
import 'package:flutter/material.dart';

// Assume isFavorite is defined elsewhere
// bool isFavorite = false;

AnimatedCrossFade(
  firstChild: const Icon(Icons.favorite_border, size: 32),
  secondChild: const Icon(Icons.favorite, size: 32, color: Colors.red),
  crossFadeState: isFavorite ? CrossFadeState.showSecond : CrossFadeState.showFirst,
  duration: const Duration(milliseconds: 300),
)
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

5. Explicit Animations

(1) AnimationController + Tween + Curve

Component Responsibility
AnimationController Controls animation timing, direction, and state
Tween<T> Defines start and end values
CurvedAnimation Applies easing curves

▶ Example

TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

: Product fly-to-cart animation

DART
import 'package:flutter/material.dart';

class FlyToCartAnimation extends StatefulWidget {
  final GlobalKey cartKey;
  final Widget child;
  final VoidCallback onComplete;
  const FlyToCartAnimation({super.key, required this.cartKey, required this.child, required this.onComplete});

  @override
  State<FlyToCartAnimation> createState() => _FlyToCartAnimationState();
}

class _FlyToCartAnimationState extends State<FlyToCartAnimation> with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: const Duration(milliseconds: 600), vsync: this);
    _animation = CurvedAnimation(parent: _controller, curve: Curves.easeInOutCubic);
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) widget.onComplete();
    });
  }

  void startFly() {
    _controller.forward(from: 0);
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(animation: _animation, builder: (context, child) {
      final cartBox = widget.cartKey.currentContext?.findRenderObject() as RenderBox?;
      if (cartBox == null) return child!;
      final cartPos = cartBox.localToGlobal(Offset.zero);
      return Transform.translate(
        offset: Offset(cartPos.dx * _animation.value, cartPos.dy * _animation.value),
        child: Transform.scale(scale: 1 - _animation.value * 0.5, child: child),
      );
    }, child: widget.child);
  }
}
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

6. Hero Transition Animations

▶ Example

TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

: Product image shared element transition

DART
import 'package:flutter/material.dart';

// Custom class definition source:
// - product: see Lesson 11 json_serializable model

// In product list
Hero(
  tag: 'product_${product.id}',
  child: ClipRRect(
    borderRadius: BorderRadius.circular(12),
    child: Image.network(product.imageUrl, fit: BoxFit.cover),
  ),
)

// In product detail page
Hero(
  tag: 'product_${product.id}',
  child: Image.network(product.imageUrl, fit: BoxFit.cover),
)
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

▶ Example

TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

: PageRouteBuilder custom transition

DART
import 'package:flutter/material.dart';

// Custom class definition source:
// - DetailPage/product: see Lesson 11 / Lesson 14

class SlideUpRoute extends PageRouteBuilder {
  final Widget page;
  SlideUpRoute(this.page) : super(
    pageBuilder: (context, animation, secondaryAnimation) => page,
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      return SlideTransition(
        position: Tween<Offset>(begin: const Offset(0, 1), end: Offset.zero)
            .animate(CurvedAnimation(parent: animation, curve: Curves.easeOutCubic)),
        child: child,
      );
    },
    transitionDuration: const Duration(milliseconds: 400),
  );
}

// Usage
Navigator.push(context, SlideUpRoute(DetailPage(product: product)));
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

7. Curves Easing Curves

Curve Effect Use Case
Curves.linear Constant speed Rarely used
Curves.easeIn Slow → Fast Exit
Curves.easeOut Fast → Slow Enter
Curves.easeInOut Slow → Fast → Slow General purpose
Curves.easeOutCubic Quick arrival Elastic effect
Curves.elasticOut Elastic bounce Playful animations
Curves.bounceOut Bounce Game-like feel

8. Complete Example: ShopApp Product Card Animation Suite

DART
import 'package:flutter/material.dart';

// Custom class definition source:
// - Product: see Lesson 11 json_serializable model

class AnimatedProductCard extends StatefulWidget {
  final Product product;
  final VoidCallback onAddToCart;
  const AnimatedProductCard({super.key, required this.product, required this.onAddToCart});

  @override
  State<AnimatedProductCard> createState() => _AnimatedProductCardState();
}

class _AnimatedProductCardState extends State<AnimatedProductCard> with SingleTickerProviderStateMixin {
  bool _isFavorite = false;
  bool _isAdded = false;
  late AnimationController _scaleController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _scaleController = AnimationController(duration: const Duration(milliseconds: 200), vsync: this);
    _scaleAnimation = Tween<double>(begin: 1.0, end: 0.95).animate(
      CurvedAnimation(parent: _scaleController, curve: Curves.easeInOut));
  }

  void _onTap() {
    _scaleController.forward().then((_) => _scaleController.reverse());
  }

  void _addToCart() {
    setState(() => _isAdded = true);
    widget.onAddToCart();
    Future.delayed(const Duration(seconds: 2), () => setState(() => _isAdded = false));
  }

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

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) => _scaleController.forward(),
      onTapUp: (_) => _scaleController.reverse(),
      onTapCancel: () => _scaleController.reverse(),
      child: ScaleTransition(
        scale: _scaleAnimation,
        child: Card(
          clipBehavior: Clip.antiAlias,
          child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
            Expanded(flex: 3, child: Stack(children: [
              Hero(tag: 'product_${widget.product.id}',
                child: Image.network(widget.product.imageUrl, fit: BoxFit.cover, width: double.infinity)),
              Positioned(top: 8, right: 8,
                child: AnimatedSwitcher(duration: const Duration(milliseconds: 300),
                  child: IconButton(key: ValueKey(_isFavorite),
                    icon: Icon(_isFavorite ? Icons.favorite : Icons.favorite_border,
                      color: _isFavorite ? Colors.red : Colors.white),
                    onPressed: () => setState(() => _isFavorite = !_isFavorite),
                    style: IconButton.styleFactory(backgroundColor: Colors.white70)))),
            ]),
            Expanded(flex: 2, child: Padding(padding: const EdgeInsets.all(8), child: Column(
              crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text(widget.product.name, maxLines: 1, overflow: TextOverflow.ellipsis),
                const Spacer(),
                Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                  Text('\$${widget.product.price.toStringAsFixed(2)}', style: const TextStyle(color: Colors.green)),
                  AnimatedSwitcher(duration: const Duration(milliseconds: 300),
                    child: _isAdded ? const Icon(Icons.check_circle, color: Colors.green, key: ValueKey('added'))
                        : IconButton(icon: const Icon(Icons.add_shopping_cart, size: 20),
                            onPressed: _addToCart, key: const ValueKey('add'))),
                ]),
              ])))),
          ]),
        ),
      ),
    );
  }
}
TEXT
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.

❓ FAQ

Q How to choose between implicit and explicit animations?
A Use implicit when possible (simpler and safer); use explicit when you need looping, reversing, or precise control.
Q Must AnimationController be disposed in dispose()?
A Yes. Not disposing causes memory leaks. Use SingleTickerProviderStateMixin to provide vsync.
Q What's the difference between AnimatedBuilder and AnimatedWidget?
A AnimatedBuilder uses a callback pattern, while AnimatedWidget requires subclassing. AnimatedBuilder is more flexible and recommended.
Q Must the Hero tag be the same on both pages?
A Yes. Hero uses the tag to match widgets across pages — the tag must be globally unique and consistent.
Q How to optimize animation jank?
A 1) Use AnimatedBuilder to limit rebuild scope; 2) Use RepaintBoundary to isolate repaints; 3) Avoid heavy operations in animation callbacks.
Q How to orchestrate multiple animations?
A Use Interval to stagger multiple animations, or use AnimationController's addStatusListener to chain them manually.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Use AnimatedContainer to create an expandable/collapsible card that toggles height and background color on tap.
  2. Intermediate (Difficulty ⭐⭐): Implement a Hero transition animation from the product list to the detail page, with the image flying from the card position to the detail page hero image.
  3. Challenge (Difficulty ⭐⭐⭐): Implement a complete "fly to cart" animation: after tapping add-to-cart, the product thumbnail flies from the card to the AppBar cart icon, shrinking and fading out during flight.

← Previous Lesson | Next Lesson →

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏