Flutter AnimatedSwitcher Widget: Managing Simple Animations in Flutter
Flutter has many widgets that help developers create beautiful animations with ease, and the AnimatedSwitcher widget is one of them. The AnimatedSwitcher widget provides a smooth transition between two or more widgets by animating the size, location, and opacity of the widgets.
One of the significant advantages of the AnimatedSwitcher widget is that it can manage the animations automatically, eliminating the need to create complex animations by hand.
Here is an example of how to use the AnimatedSwitcher widget to switch between two widgets:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'AnimatedSwitcher Demo',
home: AnimatedSwitcherDemo(),
);
}
}
class AnimatedSwitcherDemo extends StatefulWidget {
@override
_AnimatedSwitcherDemoState createState() => _AnimatedSwitcherDemoState();
}
class _AnimatedSwitcherDemoState extends State {
bool _isFirstWidgetVisible = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedSwitcher Demo'),
),
body: Center(
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 500),
child: _isFirstWidgetVisible
? Container(
key: ValueKey(1),
height: 100,
width: 100,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(50),
),
)
: Container(
key: ValueKey(2),
height: 150,
width: 150,
decoration: BoxDecoration(
color: Colors.redAccent,
borderRadius: BorderRadius.circular(75),
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_isFirstWidgetVisible = !_isFirstWidgetVisible;
});
},
child: Icon(Icons.swap_horiz),
),
);
}
}
In this example, we use the AnimatedSwitcher widget to switch between two containers of different sizes and colors. This transition is triggered by the FloatingActionButton that changes the `_isFirstWidgetVisible` boolean when clicked, making the AnimatedSwitcher switch between the two containers.
In the AnimatedSwitcher widget, we set the duration of the animation with the `duration` property and provide a `child` property that changes according to the `_isFirstWidgetVisible` boolean value.
The AnimatedSwitcher widget also provides us with customization options through callback functions that we can use to further customize our animations. These callback functions include `transitionBuilder`, `layoutBuilder`, and `switchOutCurve`.
In conclusion, the AnimatedSwitcher widget is a powerful tool for creating smooth and simple animations in Flutter effortlessly. With its built-in animation management feature and customizable options, Flutter developers can create beautiful animations in minimal time and effort.