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
- Lesson 5: StatefulWidget & Interaction
1. What You'll Learn
- Implicit animations: AnimatedContainer, AnimatedOpacity, AnimatedSwitcher, AnimatedCrossFade
- Explicit animations: AnimationController + Tween + CurvedAnimation
- Hero transition animations and PageRouteBuilder custom page transitions
- AnimatedBuilder / AnimatedWidget for precise rebuild scope control
- ShopApp: product card fly-to-cart animation + shared element page transitions
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.
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)),
)
> 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
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]
> 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
> 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
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)),
],
]),
),
);
}
}
> 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
> 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
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),
),
);
}
}
> 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
> 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
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),
)
> 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
> 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
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);
}
}
> 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
> 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
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),
)
> 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
> 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
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)));
> 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
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'))),
]),
])))),
]),
),
),
);
}
}
> 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
📖 Summary
- Implicit animations: set a target value and Flutter handles the transition (AnimatedContainer/Switcher)
- Explicit animations: AnimationController gives full control, supporting loop and reverse
- Hero implements shared element transitions between pages
- Curves control animation pacing — easeOutCubic is the most commonly used
- AnimatedBuilder limits rebuild scope, optimizing animation performance
📝 Exercises
- Basic (Difficulty ⭐): Use AnimatedContainer to create an expandable/collapsible card that toggles height and background color on tap.
- 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.
- 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.