AnimationController and Tween in Flutter: solved exercise

AnimationController and Tween in Flutter: solved exercise

Implicit animations (AnimatedContainer, TweenAnimationBuilder) are convenient but limited: they don’t support loops, manual reversal, staggered sequences, or precise time control. For those cases, use explicit animations: AnimationController + Tween + AnimatedBuilder.

Problem statement

Implement three explicit animation demos:

  1. Custom spinner with a continuously looping AnimationController.
  2. 3D flip card with AnimationController + Matrix4Transform.
  3. Staggered entry of five elements with Interval and a single controller.

Dependencies

Flutter SDK only.

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import 'dart:math';
import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: _DemoPage()));

class _DemoPage extends StatelessWidget {
  const _DemoPage();

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('AnimationController demo'),
          bottom: const TabBar(tabs: [
            Tab(text: 'Spinner'),
            Tab(text: 'Flip'),
            Tab(text: 'Staggered'),
          ]),
        ),
        body: const TabBarView(children: [
          SpinnerPage(),
          FlipCardPage(),
          StaggeredPage(),
        ]),
      ),
    );
  }
}

// ── 1. Custom spinner ──────────────────────────────────────────────────────────
class SpinnerPage extends StatefulWidget {
  const SpinnerPage({super.key});
  @override
  State<SpinnerPage> createState() => _SpinnerPageState();
}

class _SpinnerPageState extends State<SpinnerPage>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  // Tween: from 0 to 2π (full rotation)
  late final Animation<double> _rotation;
  late final Animation<double> _scale;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();  // infinite loop

    _rotation = Tween(begin: 0.0, end: 2 * pi).animate(
      CurvedAnimation(parent: _controller, curve: Curves.linear),
    );

    // Scale: grows and shrinks on each rotation
    _scale = TweenSequence([
      TweenSequenceItem(tween: Tween(begin: 0.8, end: 1.2), weight: 50),
      TweenSequenceItem(tween: Tween(begin: 1.2, end: 0.8), weight: 50),
    ]).animate(_controller);
  }

  @override
  void dispose() {
    _controller.dispose();  // ← always required
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AnimatedBuilder(
            animation: _controller,
            builder: (_, __) => Transform.scale(
              scale: _scale.value,
              child: Transform.rotate(
                angle: _rotation.value,
                child: Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [Colors.purple, Colors.blue, Colors.cyan],
                    ),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: const Icon(Icons.flutter_dash,
                      color: Colors.white, size: 48),
                ),
              ),
            ),
          ),
          const SizedBox(height: 24),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FilledButton(
                onPressed: () => _controller.isAnimating
                    ? _controller.stop()
                    : _controller.repeat(),
                child: AnimatedBuilder(
                  animation: _controller,
                  builder: (_, __) =>
                      Text(_controller.isAnimating ? 'Pause' : 'Resume'),
                ),
              ),
              const SizedBox(width: 12),
              OutlinedButton(
                onPressed: () => _controller.reset(),
                child: const Text('Reset'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

// ── 2. 3D flip card ────────────────────────────────────────────────────────────
class FlipCardPage extends StatefulWidget {
  const FlipCardPage({super.key});
  @override
  State<FlipCardPage> createState() => _FlipCardPageState();
}

class _FlipCardPageState extends State<FlipCardPage>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<double> _flipAngle;
  bool _showFront = true;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    _flipAngle = Tween(begin: 0.0, end: pi).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );
    // At the midpoint of the flip, switch the visible face
    _controller.addListener(() {
      if (_controller.value >= 0.5 && _showFront) {
        setState(() => _showFront = false);
      } else if (_controller.value < 0.5 && !_showFront) {
        setState(() => _showFront = true);
      }
    });
  }

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

  void _flip() {
    if (_controller.isCompleted) {
      _controller.reverse();
    } else {
      _controller.forward();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          GestureDetector(
            onTap: _flip,
            child: AnimatedBuilder(
              animation: _flipAngle,
              builder: (_, __) {
                // When the angle exceeds π/2, invert the transform
                // so the back face appears readable
                final angle = _showFront ? _flipAngle.value : _flipAngle.value - pi;
                return Transform(
                  alignment: Alignment.center,
                  transform: Matrix4.identity()
                    ..setEntry(3, 2, 0.002)  // perspective
                    ..rotateY(angle),
                  child: SizedBox(
                    width: 220,
                    height: 140,
                    child: Card(
                      elevation: 8,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16)),
                      color: _showFront ? Colors.blue : Colors.orange,
                      child: Center(
                        child: Text(
                          _showFront ? 'FRONT\n👋' : 'BACK\n🎉',
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                              fontSize: 24,
                              color: Colors.white,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
          const SizedBox(height: 24),
          FilledButton.icon(
            onPressed: _flip,
            icon: const Icon(Icons.flip),
            label: const Text('Flip card'),
          ),
        ],
      ),
    );
  }
}

// ── 3. Staggered entry with Interval ──────────────────────────────────────────
class StaggeredPage extends StatefulWidget {
  const StaggeredPage({super.key});
  @override
  State<StaggeredPage> createState() => _StaggeredPageState();
}

class _StaggeredPageState extends State<StaggeredPage>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final List<Animation<Offset>> _slides;
  late final List<Animation<double>> _fades;

  static const _items = [
    (Icons.star, 'First element'),
    (Icons.favorite, 'Second element'),
    (Icons.bolt, 'Third element'),
    (Icons.rocket_launch, 'Fourth element'),
    (Icons.emoji_events, 'Fifth element'),
  ];

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1200),
    );

    // Each element uses a different Interval within [0, 1]
    // First element: 0→0.4, second: 0.1→0.5, etc.
    _slides = List.generate(_items.length, (i) {
      final start = i * 0.15;
      final end = start + 0.4;
      return Tween(
        begin: const Offset(-1, 0),  // slides in from the left
        end: Offset.zero,
      ).animate(CurvedAnimation(
        parent: _controller,
        curve: Interval(start, end, curve: Curves.easeOut),
      ));
    });

    _fades = List.generate(_items.length, (i) {
      final start = i * 0.15;
      final end = start + 0.4;
      return Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
        parent: _controller,
        curve: Interval(start, end),
      ));
    });

    // Start when the screen is first rendered
    WidgetsBinding.instance.addPostFrameCallback((_) => _controller.forward());
  }

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

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24),
      child: Column(
        children: [
          AnimatedBuilder(
            animation: _controller,
            builder: (_, __) => Column(
              children: List.generate(_items.length, (i) {
                final (icon, label) = _items[i];
                return FadeTransition(
                  opacity: _fades[i],
                  child: SlideTransition(
                    position: _slides[i],
                    child: Card(
                      margin: const EdgeInsets.only(bottom: 12),
                      child: ListTile(
                        leading: Icon(icon, color: Theme.of(context).colorScheme.primary),
                        title: Text(label),
                      ),
                    ),
                  ),
                );
              }),
            ),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FilledButton(
                onPressed: () => _controller.forward(from: 0),
                child: const Text('Play'),
              ),
              const SizedBox(width: 12),
              OutlinedButton(
                onPressed: () => _controller.reset(),
                child: const Text('Reset'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

AnimationController lifecycle

1
2
3
4
5
6
7
initState → AnimationController(vsync: this, duration: ...)
         .forward()  .reverse()  .repeat()  .reset()
         AnimationStatus: dismissed | forward | reverse | completed
         dispose() → _controller.dispose()   ← always required

Implicit vs explicit animations

FeatureImplicit (AnimatedContainer)Explicit (AnimationController)
CodeMinimalMore verbose
LoopNo.repeat()
Manual progressNo.value, .animateTo()
SequencesNoInterval + TweenSequence
StaggeredNoOne controller, multiple Intervals
ReversalAutomatic on value change.reverse()

Common mistakes

  • Forgetting dispose(): the AnimationController holds Vsync resources from the framework. Without dispose() you have a memory leak and a console warning.
  • SingleTickerProviderStateMixin vs TickerProviderStateMixin: use Single for one controller, Ticker (without Single) for multiple controllers in the same State.
  • AnimatedBuilder without a child: if the child widget doesn’t depend on the animation, pass it as the child argument to AnimatedBuilder — Flutter reuses it without rebuilding it every frame.

Practical use

Explicit animations are used in: custom loaders, playing cards, screen entry with delay, custom page transitions, animated charts, and any animation that needs precise control or synchronization with external events.

Guided practice and next step

FAQ

Do I need one AnimationController per animation?

No. A single controller can drive multiple Tweens with different Intervals. For completely independent animations (different durations, different triggers), use separate controllers with TickerProviderStateMixin.

What is vsync?

vsync ties the controller to the device’s rendering cycle (typically 60 fps). Without vsync, animations would consume CPU even when the screen is hidden. SingleTickerProviderStateMixin implements TickerProvider automatically.

Can I use AnimationController outside a StatefulWidget?

Yes, with flutter_hooks (useAnimationController) or Riverpod using a StateNotifier that extends TickerProviderStateMixin. However, you must ensure dispose() is called in both cases.