The AnimatedSwitcher widget in Flutter is used to animate the transition between two or more widgets when the child widget of the AnimatedSwitcher changes. It's commonly used to provide smooth transitions between different views or components within an app.
Attributes:
child (Widget):
- The current child widget of the AnimatedSwitcher. When this child widget changes, the transition animation occurs.
duration (Duration):
- The duration of the transition animation between child widgets.
reverseDuration (Duration):
- The duration of the transition animation when the child widget is removed from the AnimatedSwitcher.
transitionBuilder (AnimatedSwitcherTransitionBuilder):
- A builder function that defines the transition animation between the old and new child widgets. This allows for customizing the animation effect.
switchInCurve (Curve):
- The animation curve for transitioning in the new child widget.
switchOutCurve (Curve):
- The animation curve for transitioning out the old child widget.
layoutBuilder (AnimatedLayoutBuilder):
- A builder function that defines the layout of the child widgets within the AnimatedSwitcher.
Example:
import 'package:flutter/material.dart';
class AnimatedSwitcherExample extends StatefulWidget {
@override
_AnimatedSwitcherExampleState createState() => _AnimatedSwitcherExampleState();
}
class _AnimatedSwitcherExampleState extends State<AnimatedSwitcherExample> {
bool _showFirst = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedSwitcher Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSwitcher(
duration: Duration(seconds: 1),
transitionBuilder: (child, animation) => ScaleTransition(
scale: animation,
child: child,
),
child: _showFirst
? Container(
key: ValueKey(1),
width: 200,
height: 200,
color: Colors.blue,
child: Center(
child: Text(
'First Widget',
style: TextStyle(color: Colors.white),
),
),
)
: Container(
key: ValueKey(2),
width: 200,
height: 200,
color: Colors.green,
child: Center(
child: Text(
'Second Widget',
style: TextStyle(color: Colors.white),
),
),
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
setState(() {
_showFirst = !_showFirst;
});
},
child: Text('Switch Widget'),
),
],
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: AnimatedSwitcherExample(),
));
}
In this example:
An AnimatedSwitcher widget is used to animate the transition between two container widgets.
The duration attribute is set to Duration(seconds: 1), specifying the duration of the transition animation.
The transitionBuilder attribute is set to a ScaleTransition, which scales the child widget during the transition.
When the user presses the elevated button, the _showFirst flag is toggled, triggering the transition animation between the two container widgets.