TweenAnimationBuilder widget and Attributes

TweenAnimationBuilder widget and Attributes

ยท

2 min read

The TweenAnimationBuilder widget in Flutter is a powerful tool for creating smooth and dynamic animations by interpolating values between a range defined by a Tween. It simplifies the animation process by eliminating the need for a separate AnimationController.

Key Attributes of the TweenAnimationBuilder Widget:

  1. tween (Tween<T>):

    • Defines the range of values over which the animation will occur.
  2. duration (Duration):

    • Specifies the total duration of the animation.
  3. builder (Widget Function(BuildContext, T, Widget?):

    • A callback function responsible for building the widget tree during each animation frame.
  4. onEnd (VoidCallback?):

    • A callback function invoked when the animation completes.

Example Usage:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double _opacity = 0.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TweenAnimationBuilder Example'),
      ),
      body: Center(
        child: TweenAnimationBuilder(
          duration: Duration(seconds: 2),
          tween: Tween<double>(begin: 0.0, end: 1.0),
          builder: (BuildContext context, double value, Widget? child) {
            _opacity = value;
            return Opacity(
              opacity: _opacity,
              child: Container(
                width: 200,
                height: 200,
                color: Colors.blue,
              ),
            );
          },
          onEnd: () {
            // Animation completed
            print('Animation completed');
          },
        ),
      ),
    );
  }
}

In this example, we use TweenAnimationBuilder to create a simple opacity animation. The tween attribute defines the range of values (opacity from 0.0 to 1.0), the duration specifies the total duration of the animation, and the builder callback constructs the widget tree during each animation frame. The opacity of a blue container is animated, and the onEnd callback is invoked when the animation completes. This showcases how TweenAnimationBuilder facilitates the creation of dynamic animations with minimal code.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย