AnimationController y Tween en Flutter: ejercicio resuelto

AnimationController y Tween en Flutter: ejercicio resuelto

Las animaciones implícitas (AnimatedContainer, TweenAnimationBuilder) son cómodas pero limitadas: no permiten bucles, reversión manual, secuencias escalonadas ni control preciso del tiempo. Para esos casos se usan animaciones explícitas: AnimationController + Tween + AnimatedBuilder.

Enunciado

Implementa tres demostraciones de animaciones explícitas:

  1. Spinner personalizado con AnimationController en bucle continuo.
  2. Tarjeta flip 3D con AnimationController + Matrix4Transform.
  3. Entrada escalonada (staggered) de cinco elementos con Interval y un solo controlador.

Dependencias

Solo Flutter SDK.

Solución completa

  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. Spinner personalizado ───────────────────────────────────────────────────
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: de 0 a 2π (vuelta completa)
  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();  // bucle infinito

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

    // Escala: crece y encoge en cada vuelta
    _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();  // ← siempre obligatorio
    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 ? 'Pausar' : 'Reanudar'),
                ),
              ),
              const SizedBox(width: 12),
              OutlinedButton(
                onPressed: () => _controller.reset(),
                child: const Text('Reset'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

// ── 2. Tarjeta flip 3D ─────────────────────────────────────────────────────────
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),
    );
    // A mitad del flip, cambiar la cara visible
    _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: (_, __) {
                // Cuando el ángulo supera π/2, invertimos la transformación
                // para que la cara trasera aparezca legible
                final angle = _showFront ? _flipAngle.value : _flipAngle.value - pi;
                return Transform(
                  alignment: Alignment.center,
                  transform: Matrix4.identity()
                    ..setEntry(3, 2, 0.002)  // perspectiva
                    ..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 ? 'FRENTE\n👋' : 'DORSO\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('Voltear tarjeta'),
          ),
        ],
      ),
    );
  }
}

// ── 3. Entrada escalonada con 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, 'Primer elemento'),
    (Icons.favorite, 'Segundo elemento'),
    (Icons.bolt, 'Tercer elemento'),
    (Icons.rocket_launch, 'Cuarto elemento'),
    (Icons.emoji_events, 'Quinto elemento'),
  ];

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

    // Cada elemento usa un Interval diferente dentro del rango [0, 1]
    // El primer elemento empieza de 0→0.4, el segundo de 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),  // viene desde la izquierda
        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),
      ));
    });

    // Iniciar al entrar en la pantalla
    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('Reproducir'),
              ),
              const SizedBox(width: 12),
              OutlinedButton(
                onPressed: () => _controller.reset(),
                child: const Text('Reset'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

Ciclo de vida del AnimationController

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

Comparativa: implícitas vs explícitas

CaracterísticaImplícitas (AnimatedContainer)Explícitas (AnimationController)
CódigoMínimoMás extenso
BucleNo.repeat()
Progreso manualNo.value, .animateTo()
SecuenciasNoInterval + TweenSequence
EscalonadoNoUn controlador, múltiples Interval
ReversiónAutomática al cambiar valor.reverse()

Errores frecuentes

  • Olvidar dispose(): el AnimationController retiene recursos Vsync del framework. Sin dispose() tienes un memory leak y una advertencia en consola.
  • SingleTickerProviderStateMixin vs TickerProviderStateMixin: usa Single cuando tienes un solo controlador, Ticker (sin Single) cuando tienes varios en el mismo State.
  • AnimatedBuilder sin children: si el widget hijo no depende de la animación, pásalo como child al AnimatedBuilder — Flutter lo reutiliza sin reconstruirlo en cada frame.

Aplicación práctica

Las animaciones explícitas se usan en: loaders personalizados, cartas de juego, entradas de pantalla con retardo, transiciones de página custom, gráficos animados y cualquier animación que necesite control preciso o sincronización con eventos externos.

Siguiente ejercicio recomendado

Práctica guiada y siguiente paso

FAQ

¿Necesito un AnimationController por animación?

No. Un solo controlador puede alimentar múltiples Tween con distintos Interval. Para animaciones completamente independientes (distintas duraciones, distintos triggers), usa controladores separados con TickerProviderStateMixin.

¿Qué es vsync?

El vsync vincula el controlador al ciclo de renderizado del dispositivo (normalmente 60 fps). Sin vsync, las animaciones consumirían CPU incluso en pantallas ocultas. SingleTickerProviderStateMixin implementa TickerProvider de forma automática.

¿Puedo usar AnimationController fuera de un StatefulWidget?

Sí, con flutter_hooks (useAnimationController) o con Riverpod usando un StateNotifier que extiende TickerProviderStateMixin. Sin embargo, hay que asegurarse de llamar dispose() en ambos casos.