Mastering Tween Animations in Flutter with TweenAnimationBuilder

Introduction:

Flutter offers a rich set of animation capabilities to bring your user interfaces to life. One powerful tool in the Flutter animation toolbox is the TweenAnimationBuilder widget. In this blog post, we will explore how to leverage the TweenAnimationBuilder widget to create smooth and dynamic tween animations in your Flutter applications. We'll dive into its usage, explain the core concepts, and provide practical examples to help you get started.

Understanding Tween Animations:

Tween animations interpolate between two values over a specified duration, creating smooth transitions between different states. Flutter's Tween class provides interpolation functions that generate values between a specified start and end value. By combining the Tween class with the TweenAnimationBuilder widget, you can easily create customized and reusable animations.

Using the TweenAnimationBuilder:

The TweenAnimationBuilder widget takes in four essential parameters:

  1. duration: The duration of the animation, specifying how long the transition should take.
  2. builder: A callback function that provides the current animation value and returns a widget to build.
  3. tween: The Tween object that defines the range of values to interpolate.
  4. onEnd: An optional callback function that is triggered when the animation completes.

Example Usage:

Let's explore a practical example of using the TweenAnimationBuilder widget to animate the opacity of a widget over time:

TweenAnimationBuilder<double>(
  duration: Duration(seconds: 2),
  tween: Tween<double>(begin: 0, end: 1),
  builder: (context, value, child) {
    return Opacity(
      opacity: value,
      child: Container(
        width: 200,
        height: 200,
        color: Colors.blue,
      ),
    );
  },
)

In this example, we define a TweenAnimationBuilder with a duration of 2 seconds and a Tween<double> that interpolates the opacity value from 0 to 1. Inside the builder function, we receive the current interpolated value as value and use it to animate the opacity of the Container widget. As the animation progresses, the opacity of the container gradually increases, resulting in a smooth fade-in effect.

Customizing Animations:

The TweenAnimationBuilder widget provides endless possibilities for customizing animations. You can apply the Tween class to various properties such as size, position, color, rotation, and more. By combining different tweens, you can create complex and engaging animations that enhance the user experience.

TweenAnimationBuilder<Color>(
  duration: Duration(seconds: 1),
  tween: ColorTween(begin: Colors.red, end: Colors.blue),
  builder: (context, value, child) {
    return Container(
      width: 200,
      height: 200,
      color: value,
    );
  },
)

In this example, we use the ColorTween to interpolate between two colors, resulting in a smooth color transition of the Container widget from red to blue over a duration of 1 second.

A Example App Explain TweenAnimationBuilder:

import 'package:flutter/material.dart';


void main() {
  runApp(const TweenAnimationApp());
}


class TweenAnimationApp extends StatelessWidget {
  const TweenAnimationApp({super.key});


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tween Animation Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const TweenAnimationScreen(),
    );
  }
}


class ColorTweenPlus extends Tween<Color> {
  ColorTweenPlus({required Color begin, required Color end})
      : super(begin: begin, end: end);


  @override
  Color lerp(double t) {
    return Color.lerp(begin, end, t)!;
  }
}


class TweenAnimationScreen extends StatefulWidget {
  const TweenAnimationScreen({super.key});


  @override
  _TweenAnimationScreenState createState() => _TweenAnimationScreenState();
}


class _TweenAnimationScreenState extends State<TweenAnimationScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _sizeAnimation;
  late Animation<Color?> _colorAnimation;


  @override
  void initState() {
    super.initState();


    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    );


    final sizeTween = Tween<double>(begin: 100, end: 300);
    final colorTween = ColorTweenPlus(
      begin: const Color(0xff0e7ac7),
      end: const Color(0xff777777),
    );


    _sizeAnimation = sizeTween.animate(_animationController);
    _colorAnimation = colorTween.animate(_animationController);


    _animationController.repeat(reverse: true);
  }


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


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Tween Animation Example'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: _animationController,
          builder: (context, child) {
            return Container(
              width: _sizeAnimation.value,
              height: _sizeAnimation.value,
              decoration: BoxDecoration(
                color: _colorAnimation.value ?? Colors.transparent,
                shape: BoxShape.circle,
              ),
            );
          },
        ),
      ),
    );
  }
}

In this example, we create a Flutter app with a single screen called TweenAnimationScreen. Inside the screen's state, we define an AnimationController that controls the animation. We also define two Tween objects: one for size interpolation (sizeTween) and another for color interpolation (colorTween).

Inside the initState() method, we set up the animations by assigning the tweens to the respective Animation objects (_sizeAnimation and _colorAnimation) using the animate() method of the Tween class. We also configure the animation controller to repeat the animation in reverse.

In the build() method, we use the AnimatedBuilder widget to rebuild the UI whenever the animation value changes. The AnimatedBuilder takes the animation controller and a builder function. Inside the builder function, we create a Container widget and apply the animated values to the width, height, and color properties using _sizeAnimation.value and _colorAnimation.value respectively.

As a result, when you run the app, you will see a circular container widget that smoothly animates its size and color between the specified values.

Feel free to modify the example code and experiment with different properties, tweens, and animations to create custom animations tailored to your app's requirements.

I hope this example helps you understand how to use the TweenAnimationBuilder widget for tween animations in Flutter!

Conclusion:

The TweenAnimationBuilder widget empowers Flutter developers to create visually appealing and dynamic animations effortlessly. By leveraging the power of the Tween class and providing a builder function, you can easily interpolate between different values and create smooth transitions in your UI.

In this blog post, we explored the usage of the TweenAnimationBuilder widget and demonstrated practical examples of animating opacity and colors. Remember to experiment with various properties and tweens to create custom animations tailored to your application's needs.

Now armed with the knowledge of TweenAnimationBuilder, you can add delightful animations that captivate your users and provide a polished user experience in your Flutter applications. Happy animating!

GitHub:

View GitHub

Description of the image

Related Posts