Flutter - How to enable AnimatedOpacity automatically?

To make a StatelessWidget or StatefulWidget fade in automatically on creation, TweenAnimationBuilder provides an even easier solution:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
        tween: Tween<double>(begin: 0.0, end: 1.0),
        curve: Curves.ease,
        duration: const Duration(seconds: 1),
        builder: (BuildContext context, double opacity, Widget? child) {
          return Opacity(
              opacity: opacity,
              child: Container(width: 20, height: 20, color: Colors.red)
          );
    });
  }
}

See my Codepen for a complete example: https://codepen.io/atok/pen/BaZVRPr

Best regards


Instead of AnimatedOpacity, use a FadeTransition widget. This gives you manual control over the animation:

  @override
  Widget build(BuildContext context) {
    return FadeTransition(
      opacity: animationController.drive(CurveTween(curve: Curves.easeOut)),
      child: ...,
    );
  }