Bird
Raised Fist0
Fluttermobile~20 mins

Tween animations in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Color Tween Animation
This screen shows a square that smoothly changes its color from blue to red and back repeatedly using a tween animation.
Target UI
┌─────────────────────────────┐
│        Color Tween          │
│                             │
│          ■■■■■■■■           │
│          ■■■■■■■■           │
│          ■■■■■■■■           │
│                             │
│  [Animate Color]             │
└─────────────────────────────┘
A square container of size 150x150 pixels in the center
A button labeled 'Animate Color' below the square
When the button is pressed, the square color animates smoothly from blue to red and back repeatedly
Use Tween animation with AnimationController and ColorTween
Animation should loop continuously until stopped
Button toggles animation start and stop
Starter Code
Flutter
import 'package:flutter/material.dart';

class ColorTweenAnimationScreen extends StatefulWidget {
  @override
  State<ColorTweenAnimationScreen> createState() => _ColorTweenAnimationScreenState();
}

class _ColorTweenAnimationScreenState extends State<ColorTweenAnimationScreen> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Color?> _colorAnimation;

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

    _colorAnimation = ColorTween(begin: Colors.blue, end: Colors.red).animate(_controller);

    // TODO: Add animation status listener to loop animation
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Color Tween Animation')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // TODO: Add AnimatedBuilder to rebuild Container with animated color
            Container(
              width: 150,
              height: 150,
              color: Colors.blue,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // TODO: Add button logic to start/stop animation
              },
              child: const Text('Animate Color'),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

class ColorTweenAnimationScreen extends StatefulWidget {
  @override
  State<ColorTweenAnimationScreen> createState() => _ColorTweenAnimationScreenState();
}

class _ColorTweenAnimationScreenState extends State<ColorTweenAnimationScreen> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Color?> _colorAnimation;
  bool isAnimating = false;

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

    _colorAnimation = ColorTween(begin: Colors.blue, end: Colors.red).animate(_controller);

    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        _controller.forward();
      }
    });
  }

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

  void _toggleAnimation() {
    if (isAnimating) {
      _controller.stop();
    } else {
      _controller.forward();
    }
    setState(() {
      isAnimating = !isAnimating;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Color Tween Animation')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            AnimatedBuilder(
              animation: _colorAnimation,
              builder: (context, child) {
                return Container(
                  width: 150,
                  height: 150,
                  color: _colorAnimation.value,
                );
              },
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _toggleAnimation,
              child: Text(isAnimating ? 'Stop Animation' : 'Animate Color'),
            ),
          ],
        ),
      ),
    );
  }
}

We use an AnimationController to control the animation timing. The ColorTween smoothly changes the color from blue to red. We listen to the animation status to reverse direction when it reaches the end or start, creating a continuous loop. The AnimatedBuilder rebuilds the square container whenever the color changes. The button toggles the animation on and off, updating its label accordingly.

Final Result
Completed Screen
┌─────────────────────────────┐
│        Color Tween          │
│                             │
│          ■■■■■■■■           │
│          ■■■■■■■■           │
│          ■■■■■■■■           │
│                             │
│  [Animate Color]             │
└─────────────────────────────┘
Tap 'Animate Color' button: The square color smoothly changes from blue to red and back repeatedly.
Button label changes to 'Stop Animation' while animating.
Tap 'Stop Animation' button: The animation stops and the square color stays at current color.
Button label changes back to 'Animate Color'.
Stretch Goal
Add a slider to control the animation speed from 0.5 seconds to 5 seconds.
💡 Hint
Use the slider value to update the AnimationController's duration dynamically and restart the animation if running.

Practice

(1/5)
1. What is the main purpose of a Tween in Flutter animations?
easy
A. To start and stop the animation
B. To control the speed of the animation
C. To define the range of values an animation will interpolate between
D. To display the animation on the screen

Solution

  1. Step 1: Understand Tween's role

    A Tween defines the start and end values for an animation, like from 0 to 100.
  2. Step 2: Differentiate from controller

    The AnimationController controls timing, not the value range.
  3. Final Answer:

    To define the range of values an animation will interpolate between -> Option C
  4. Quick Check:

    Tween = value range [OK]
Hint: Tween sets value range, controller sets timing [OK]
Common Mistakes:
  • Confusing Tween with AnimationController
  • Thinking Tween controls animation speed
  • Assuming Tween displays animation
2. Which of the following is the correct way to create a Tween from 0.0 to 1.0 in Flutter?
easy
A. Tween(begin: 0.0, end: 1.0)
B. Tween(start: 0.0, finish: 1.0)
C. Tween(from: 0, to: 1)
D. Tween(range: 0 to 1)

Solution

  1. Step 1: Recall Tween constructor parameters

    The Tween constructor uses named parameters begin and end to set start and end values.
  2. Step 2: Check options for correct syntax

    Only Tween(begin: 0.0, end: 1.0) uses begin and end correctly with valid values.
  3. Final Answer:

    Tween(begin: 0.0, end: 1.0) -> Option A
  4. Quick Check:

    Correct parameters = begin, end [OK]
Hint: Use begin and end for Tween values [OK]
Common Mistakes:
  • Using wrong parameter names like start or from
  • Using invalid syntax like 'range: 0 to 1'
  • Mixing integer and double types incorrectly
3. Given this code snippet, what will be the value of animation.value when the controller is halfway through its duration?
final controller = AnimationController(vsync: this, duration: Duration(seconds: 2));
final animation = Tween(begin: 10.0, end: 20.0).animate(controller);
controller.value = 0.5;
medium
A. 10.0
B. 15.0
C. 20.0
D. 30.0

Solution

  1. Step 1: Understand Tween interpolation

    The Tween goes from 10.0 to 20.0, so halfway means halfway between these values.
  2. Step 2: Calculate halfway value

    Halfway is (10.0 + 20.0) / 2 = 15.0.
  3. Final Answer:

    15.0 -> Option B
  4. Quick Check:

    Halfway value = 15.0 [OK]
Hint: Halfway means average of begin and end [OK]
Common Mistakes:
  • Using controller.value directly instead of interpolated value
  • Choosing begin or end value instead of midpoint
  • Adding values incorrectly
4. What is wrong with this Flutter Tween animation code?
final controller = AnimationController(vsync: this, duration: Duration(seconds: 1));
final animation = Tween(begin: 0.0, end: 100.0).animate(controller);
controller.forward();
print(animation.value);
medium
A. Animation value is not updated immediately after forward()
B. AnimationController requires a TickerProvider for vsync
C. Tween values must be doubles, not integers
D. Missing dispose() call for controller

Solution

  1. Step 1: Check animation timing

    Calling controller.forward() starts animation asynchronously; animation.value won't update instantly.
  2. Step 2: Understand print timing

    Printing animation.value immediately after forward() shows the initial value, not the animated value.
  3. Final Answer:

    Animation value is not updated immediately after forward() -> Option A
  4. Quick Check:

    Animation updates over time, not instantly [OK]
Hint: Animation updates asynchronously after forward() [OK]
Common Mistakes:
  • Expecting animation.value to change immediately
  • Confusing vsync errors with animation timing
  • Ignoring controller lifecycle management
5. You want to animate a color change smoothly from red to blue over 3 seconds using a Tween. Which of the following code snippets correctly sets up the Tween animation?
hard
A. final animation = ColorTween(start: Colors.red, finish: Colors.blue).animate(controller);
B. final animation = Tween(begin: Colors.red, end: Colors.blue).animate(controller);
C. final animation = Tween<Color>(begin: Colors.red, end: Colors.blue).animate(controller);
D. final animation = ColorTween(begin: Colors.red, end: Colors.blue).animate(controller);

Solution

  1. Step 1: Identify correct Tween type for colors

    Flutter provides ColorTween specifically for color interpolation.
  2. Step 2: Check constructor parameters

    ColorTween uses begin and end, not start or finish.
  3. Final Answer:

    final animation = ColorTween(begin: Colors.red, end: Colors.blue).animate(controller); -> Option D
  4. Quick Check:

    Use ColorTween with begin and end [OK]
Hint: Use ColorTween with begin/end for colors [OK]
Common Mistakes:
  • Using generic Tween for colors without specifying type
  • Using wrong parameter names like start or finish
  • Not using ColorTween for color animations
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard