Bird
Raised Fist0
Fluttermobile~20 mins

AnimatedBuilder in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Rotating Square Animation
This screen shows a square that continuously rotates using AnimatedBuilder. It demonstrates how to animate a widget smoothly with Flutter's animation system.
Target UI
---------------------
|                   |
|      ■            |
|                   |
|                   |
|                   |
|                   |
---------------------
Use AnimatedBuilder to animate a square rotation.
The square should rotate continuously clockwise.
Use an AnimationController and Tween for rotation.
The square should be centered on the screen.
Add a button to start and stop the rotation.
Starter Code
Flutter
import 'package:flutter/material.dart';

class RotatingSquareScreen extends StatefulWidget {
  @override
  State<RotatingSquareScreen> createState() => _RotatingSquareScreenState();
}

class _RotatingSquareScreenState extends State<RotatingSquareScreen> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 4),
    );
    _animation = Tween<double>(begin: 0, end: 2 * 3.14159).animate(_controller);

    // TODO: Start the animation looping
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Rotating Square Animation')),
      body: Center(
        // TODO: Use AnimatedBuilder here to rotate a square
        child: Container(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // TODO: Start or stop the animation
        },
        child: const Icon(Icons.play_arrow),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

class RotatingSquareScreen extends StatefulWidget {
  @override
  State<RotatingSquareScreen> createState() => _RotatingSquareScreenState();
}

class _RotatingSquareScreenState extends State<RotatingSquareScreen> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 4),
    );
    _animation = Tween<double>(begin: 0, end: 2 * 3.14159).animate(_controller);

    _controller.repeat();
  }

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

  void _toggleAnimation() {
    if (_controller.isAnimating) {
      _controller.stop();
    } else {
      _controller.repeat();
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Rotating Square Animation')),
      body: Center(
        child: AnimatedBuilder(
          animation: _animation,
          builder: (context, child) {
            return Transform.rotate(
              angle: _animation.value,
              child: child,
            );
          },
          child: Container(
            width: 100,
            height: 100,
            color: Colors.blue,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _toggleAnimation,
        child: Icon(_controller.isAnimating ? Icons.pause : Icons.play_arrow),
        tooltip: _controller.isAnimating ? 'Pause' : 'Play',
      ),
    );
  }
}

We create an AnimationController that runs for 4 seconds and loops continuously using repeat(). The Tween animates from 0 to 2π radians, representing a full rotation.

The AnimatedBuilder listens to the animation and rebuilds its child with a rotation transform. This way, the square rotates smoothly.

The floating action button toggles the animation on and off by starting or stopping the controller. The icon changes accordingly to show play or pause.

This example shows how AnimatedBuilder helps separate animation logic from widget building, making animations efficient and easy to manage.

Final Result
Completed Screen
---------------------
|                   |
|        ■          |
|                   |
|                   |
|                   |
|                   |
---------------------
[FloatingActionButton: Play/Pause Icon]
The blue square in the center rotates continuously clockwise.
Tapping the floating action button pauses or resumes the rotation.
The button icon changes between play and pause accordingly.
Stretch Goal
Add a slider to control the rotation speed dynamically.
💡 Hint
Use the slider's value to update the AnimationController's duration and restart the animation.

Practice

(1/5)
1. What is the main purpose of using AnimatedBuilder in Flutter?
easy
A. To handle user input events
B. To create static UI elements without animation
C. To efficiently rebuild only parts of the UI that change during animation
D. To manage app navigation between screens

Solution

  1. Step 1: Understand AnimatedBuilder's role

    AnimatedBuilder is designed to rebuild only the widgets that depend on the animation value, improving performance.
  2. Step 2: Compare with other options

    Options B, C, and D describe unrelated Flutter features like static UI, input handling, and navigation.
  3. Final Answer:

    To efficiently rebuild only parts of the UI that change during animation -> Option C
  4. Quick Check:

    AnimatedBuilder optimizes UI updates = A [OK]
Hint: AnimatedBuilder rebuilds only animated parts [OK]
Common Mistakes:
  • Thinking AnimatedBuilder rebuilds the whole UI
  • Confusing AnimatedBuilder with navigation widgets
  • Assuming it handles user input
2. Which of the following is the correct way to declare an AnimatedBuilder widget?
easy
A. AnimatedBuilder(animation: builder, child: myAnimation, builder: context)
B. AnimatedBuilder(child: myAnimation, animation: builder, builder: childWidget)
C. AnimatedBuilder(builder: myAnimation, animation: childWidget, child: context)
D. AnimatedBuilder(animation: myAnimation, builder: (context, child) => Widget, child: childWidget)

Solution

  1. Step 1: Recall AnimatedBuilder parameters

    AnimatedBuilder requires an animation, a builder function with context and child, and optionally a child widget.
  2. Step 2: Match correct parameter order and names

    AnimatedBuilder(animation: myAnimation, builder: (context, child) => Widget, child: childWidget) correctly uses animation, builder, and child parameters in proper order and types.
  3. Final Answer:

    AnimatedBuilder(animation: myAnimation, builder: (context, child) => Widget, child: childWidget) -> Option D
  4. Quick Check:

    Correct parameter names and order = D [OK]
Hint: Remember: animation, builder, then child parameters [OK]
Common Mistakes:
  • Mixing parameter names and order
  • Passing wrong types to parameters
  • Confusing builder and child roles
3. Given this Flutter code snippet using AnimatedBuilder:
AnimatedBuilder(
  animation: animationController,
  builder: (context, child) {
    return Opacity(
      opacity: animationController.value,
      child: child,
    );
  },
  child: const Text('Hello'),
)
What will be the visible effect when the animation runs from 0 to 1?
medium
A. The text 'Hello' fades in from invisible to fully visible
B. The text 'Hello' moves from left to right
C. The text 'Hello' changes color gradually
D. The text 'Hello' scales up in size

Solution

  1. Step 1: Analyze the builder function

    The builder returns an Opacity widget with opacity set to animationController.value, which changes from 0 to 1.
  2. Step 2: Understand the effect on child

    The child is the Text widget 'Hello'. Opacity changes from transparent (0) to fully visible (1), causing a fade-in effect.
  3. Final Answer:

    The text 'Hello' fades in from invisible to fully visible -> Option A
  4. Quick Check:

    Opacity animation from 0 to 1 = fade-in [OK]
Hint: Opacity from 0 to 1 means fade-in effect [OK]
Common Mistakes:
  • Confusing opacity with movement or color
  • Ignoring the child parameter usage
  • Assuming scaling instead of opacity change
4. What is wrong with this AnimatedBuilder usage?
AnimatedBuilder(
  animation: animationController,
  builder: (context) {
    return Transform.rotate(
      angle: animationController.value,
      child: Text('Rotate'),
    );
  },
)
medium
A. The builder function is missing the child parameter
B. The animationController.value cannot be used as an angle
C. Text widget cannot be used inside AnimatedBuilder
D. Transform.rotate requires a duration parameter

Solution

  1. Step 1: Check builder function signature

    The builder function must accept two parameters: context and child, but here it only has context.
  2. Step 2: Understand AnimatedBuilder usage

    Missing the child parameter can cause unnecessary rebuilds and is against the recommended pattern.
  3. Final Answer:

    The builder function is missing the child parameter -> Option A
  4. Quick Check:

    Builder needs (context, child) parameters [OK]
Hint: Builder must have (context, child) parameters [OK]
Common Mistakes:
  • Omitting the child parameter in builder
  • Misusing animation value types
  • Thinking Transform.rotate needs duration
5. You want to animate a widget's size smoothly using AnimatedBuilder with a Tween from 100 to 200 pixels. Which approach correctly optimizes performance by avoiding rebuilding the static child widget?
hard
A. Use setState inside the builder to update the child widget size
B. Pass the static child widget as the child parameter and use it inside the builder without rebuilding
C. Create the child widget inside the builder function every time it rebuilds
D. Wrap the child widget with a StatefulWidget and rebuild it manually

Solution

  1. Step 1: Understand AnimatedBuilder optimization

    Passing the static child widget as the child parameter prevents it from rebuilding on every animation tick.
  2. Step 2: Avoid rebuilding static widgets inside builder

    Creating the child inside builder causes unnecessary rebuilds, hurting performance.
  3. Final Answer:

    Pass the static child widget as the child parameter and use it inside the builder without rebuilding -> Option B
  4. Quick Check:

    Use child parameter to optimize rebuilds = C [OK]
Hint: Use child parameter to avoid rebuilding static widgets [OK]
Common Mistakes:
  • Building static widgets inside builder repeatedly
  • Using setState inside builder incorrectly
  • Misunderstanding child parameter purpose
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