AnimatedCrossFade Widget and Attributes

AnimatedCrossFade Widget and Attributes

ยท

2 min read

The AnimatedCrossFade widget in Flutter is used to smoothly transition between two children widgets with a cross-fade animation. It's commonly used to animate changes between two different states or views, providing a visually appealing transition effect.

Attributes:

  1. firstChild (Widget):

    • The widget to display when the firstCurve animation is active.
  2. secondChild (Widget):

    • The widget to display when the secondCurve animation is active.
  3. firstCurve (Curve):

    • The animation curve for transitioning from the first child to the second child.
  4. secondCurve (Curve):

    • The animation curve for transitioning from the second child to the first child.
  5. sizeCurve (Curve):

    • The animation curve for resizing the widgets during the transition.
  6. crossFadeState (CrossFadeState):

    • The state of the cross-fade animation. It can be CrossFadeState.showFirst or CrossFadeState.showSecond.
  7. duration (Duration):

    • The duration of the animation.

Example:

import 'package:flutter/material.dart';

class AnimatedCrossFadeExample extends StatefulWidget {
  @override
  _AnimatedCrossFadeExampleState createState() => _AnimatedCrossFadeExampleState();
}

class _AnimatedCrossFadeExampleState extends State<AnimatedCrossFadeExample> {
  bool _showFirst = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedCrossFade Example'),
      ),
      body: Center(
        child: AnimatedCrossFade(
          duration: Duration(seconds: 1),
          firstChild: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
            child: Center(child: Text('First Child')),
          ),
          secondChild: Container(
            width: 200,
            height: 200,
            color: Colors.green,
            child: Center(child: Text('Second Child')),
          ),
          crossFadeState: _showFirst ? CrossFadeState.showFirst : CrossFadeState.showSecond,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _showFirst = !_showFirst;
          });
        },
        child: Icon(Icons.flip),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: AnimatedCrossFadeExample(),
  ));
}

In this example, an AnimatedCrossFade widget is used to transition between two containers with different colors. The crossFadeState is toggled between showFirst and showSecond when the floating action button is pressed, triggering the cross-fade animation between the two states.

Did you find this article valuable?

Support Vinit Mepani by becoming a sponsor. Any amount is appreciated!

ย