Site icon Flutter Packages | Pub dev Packages – Flutter Mobile App World

FadeTransition Widget for Flutter

Short Intro About FadeTransition Widget

Animates the opacity of a widget. For a widget that automatically animates between the sizes of two children, fading between them, see AnimatedCrossFade.

What  FadeTransition Widget in Flutter?

FadeTransition Widget allows us to fade a widget in and out by animating their opacity. Therefore, we have to provide the opacity parameter with animation and a child widget on which the animation will be performed. But one thing, where do these animations come from? We first have to create an AnimationController using AnimationController class to set the duration and then create the animation giving the start and end opacity values. Finally, you can start the animation by calling the forward() method on the controller.

AnimationController class

A controller for an animation.

This class lets you perform tasks such as:

By default, an AnimationController linearly produces values that range from 0.0 to 1.0, during a given duration. The animation controller generates a new value whenever the device running your app is ready to display a new frame (typically, this rate is around 60 values per second).

Using Futures with AnimationController

The methods that start animations return a TickerFuture object which completes when the animation completes successfully, and never throws an error; if the animation is canceled, the future never completes. This object also has a TickerFuture.orCancel property which returns a future that completes when the animation completes successfully, and completes with an error when the animation is aborted.

This can be used to write code such as the fadeOutAndUpdateState method below.

Sample code of AnimationController

class Foo extends StatefulWidget {

  const Foo({ Key? key, required this.duration }) : super(key: key);

  final Duration duration;

  @override

  _FooState createState() => _FooState();

}

class _FooState extends State<Foo> with SingleTickerProviderStateMixin {

  late AnimationController _controller;

  @override

  void initState() {

    super.initState();

    _controller = AnimationController(

      vsync: this, // the SingleTickerProviderStateMixin

      duration: widget.duration,

    );

  }

  @override

  void didUpdateWidget(Foo oldWidget) {

    super.didUpdateWidget(oldWidget);

    _controller.duration = widget.duration;

  }

  @override

  void dispose() {

    _controller.dispose();

    super.dispose();

  }

  @override

  Widget build(BuildContext context) {

    return Container(); // …

  }

}

Here is a stateful Foo widget. Its State uses the SingleTickerProviderStateMixin to implement the necessary TickerProvider, creating its controller in the State.initState method and disposing of it in the State.dispose method. The duration of the controller is configured from a property in the Foo widget; as that changes, the State.didUpdateWidget method is used to update the controller.

The following method (for a State subclass) drives two animation controllers using Dart’s asynchronous syntax for awaiting Future objects:

Future<void> fadeOutAndUpdateState() async {

  try {

    await fadeAnimationController.forward().orCancel;

    await sizeAnimationController.forward().orCancel;

    setState(() {

      dismissed = true;

    });

  } on TickerCanceled {

    // the animation got canceled, probably because we were disposed

  }

}

How to use FadeTransition Widget

Here’s an illustration of the FadeTransition widget, with it’s opacity animated by a CurvedAnimation set to Curves.fastOutSlowIn:

Sample Code for FadeTransition Widget:

The following code implements the FadeTransition using the Flutter logo:

late final AnimationController _controller = AnimationController(

  duration: const Duration(seconds: 2),

  vsync: this,

)..repeat(reverse: true);

late final Animation<double> _animation = CurvedAnimation(

  parent: _controller,

  curve: Curves.easeIn,

);

@override

void dispose() {

  _controller.dispose();

  super.dispose();

}

@override

Widget build(BuildContext context) {

  return Container(

    color: Colors.white,

    child: FadeTransition(

      opacity: _animation,

      child: const Padding(

        padding: EdgeInsets.all(8),

        child: FlutterLogo()

      ),

    ),

  );

}

FadeTransition Widget code for Interactive App

The following code implements the FadeTransition using the Flutter logo:

import ‘package:flutter/material.dart’;

void main() => runApp(const MyApp());

/// This is the main application widget.

class MyApp extends StatelessWidget {

  const MyApp({Key? key}) : super(key: key);

  static const String _title = ‘Flutter Code Sample’;

  @override

  Widget build(BuildContext context) {

    return const MaterialApp(

      title: _title,

      home: MyStatefulWidget(),

    );

  }

}

/// This is the stateful widget that the main application instantiates.

class MyStatefulWidget extends StatefulWidget {

  const MyStatefulWidget({Key? key}) : super(key: key);

  @override

  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();

}

/// This is the private State class that goes with MyStatefulWidget.

/// AnimationControllers can be created with `vsync: this` because of TickerProviderStateMixin.

class _MyStatefulWidgetState extends State<MyStatefulWidget>

    with TickerProviderStateMixin {

  late final AnimationController _controller = AnimationController(

    duration: const Duration(seconds: 2),

    vsync: this,

  )..repeat(reverse: true);

  late final Animation<double> _animation = CurvedAnimation(

    parent: _controller,

    curve: Curves.easeIn,

  );

  @override

  void dispose() {

    _controller.dispose();

    super.dispose();

  }

  @override

  Widget build(BuildContext context) {

    return Container(

      color: Colors.white,

      child: FadeTransition(

        opacity: _animation,

        child: const Padding(padding: EdgeInsets.all(8), child: FlutterLogo()),

      ),

    );

  }

}

Output of this Sample FadeTransition Widget code:

https://dartpad.dev/embed-flutter.html?split=60&run=true&null_safety=true&sample_id=widgets.FadeTransition.1&sample_channel=master

To create a local project with this code sample, run:

flutter create –sample=widgets.FadeTransition.1 mysample

Conclusion: 

In this article, we have been discussing what is FadeTransition Widget in Flutter along with how to implement it in Flutter app with sample example source codes.

Source to get more details about the Flutter FadeTransition Widget and Class

For Animation class: https://api.flutter.dev/flutter/animation/AnimationController-class.html

FadeTransition class: https://api.flutter.dev/flutter/widgets/FadeTransition-class.html

FadeTransition class on Pub.dev: https://pub.dev/documentation/flutter_for_web/latest/widgets/FadeTransition-class.html

Readymade Sample app on Animation: https://flutterappworld.com/category/flutter-app/animation/

Exit mobile version