DEV Community

Cover image for Flutter trick: using AnimatedBuilder for efficient animations.
Reme Le Hane
Reme Le Hane

Posted on • Originally published at remejuan.substack.com

Flutter trick: using AnimatedBuilder for efficient animations.

When you want to add animations that don’t rebuild the entire widget tree, AnimatedBuilder is an efficient way to create smooth, high-performance animations.

Example: Rotating Icon Animation

This example shows how to use AnimatedBuilder to smoothly rotate an icon without rebuilding unnecessary parts of the widget tree:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Rotating Icon")),
        body: Center(child: RotatingIcon()),
      ),
    );
  }
}

class RotatingIcon extends StatefulWidget {
  @override
  _RotatingIconState createState() => _RotatingIconState();
}

class _RotatingIconState extends State<RotatingIcon>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

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

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Transform.rotate(
          angle: _controller.value * 2.0 * 3.1416, // Full circle
          child: child,
        );
      },
      child: Icon(
        Icons.sync,
        size: 100,
        color: Colors.blue,
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

AnimationController: Controls the animation’s duration and state (we set it to repeat indefinitely here).

AnimatedBuilder: Efficiently rebuilds only the parts of the widget that need updating, keeping performance smooth.

Transform.rotate: Rotates the icon based on the controller’s current animation value.

Using AnimatedBuilder like this is a highly efficient way to add animations to your Flutter app without rebuilding the widget tree, which keeps animations smooth and improves app performance.

Sentry mobile image

Is your mobile app slow? Improve performance with these key strategies.

Improve performance with key strategies like TTID/TTFD & app start analysis.

Read the blog post

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools