Welcome to Animation Series Part 2, where we’ll dive into Implicit Animations in Flutter! Building on the foundational concepts from Part 1, this section focuses on the simpler, more intuitive approach to animations that Flutter provides.
By the end of this part, you’ll have a solid understanding of how to leverage implicit animations to enhance your Flutter apps. Let’s get started!
This is the most basic and simplest approach to animate any element. It involves;
duration
parameter is required, which specifies how long the animation will take to complete.setState
is called, the widget will rebuild, and the animation will be triggered.I want to update the color of a Box from red to blue;
Here are my steps
demo_1.dart
AnimatedContainer(
height: 300,
width: 200,
duration:const Duration(milliseconds:500)
)
demo_1.dart
AnimatedContainer(
height: 300,
width: 200,
color: Colors.red,
duration:const Duration(milliseconds:500)
)
demo_1.dart
class Demo1 extends StatefulWidget {
const Demo1({super.key});
@override
State<Demo1> createState() => _Demo1State();
}
class _Demo1State extends State<Demo1> {
//This variable will be used to change the
bool isRed = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
AnimatedContainer(
duration:const Duration(milliseconds:500)
height: 300,
width: 200,
color: Colors.red,
duration:const Duration(milliseconds:500)
),
],
),
);
}
}
demo_1.dart
class Demo1 extends StatefulWidget {
const Demo1({super.key});
@override
State<Demo1> createState() => _Demo1State();
}
class _Demo1State extends State<Demo1> {
//This variable will be used to change the
bool isRed = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
AnimatedContainer(
height: 300,
width: 200,
color:isRed ? Colors.red:Colors.blue,
duration:const Duration(milliseconds:500)
),
],
),
);
}
}
class Demo1 extends StatefulWidget {
const Demo1({super.key});
@override
State<Demo1> createState() => _Demo1State();
}
class _Demo1State extends State<Demo1> {
//This variable will be used to change the
bool isRed = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
AnimatedContainer(
height: 300,
width: 200,
color:isRed ? Colors.red:Colors.blue,
duration:const Duration(milliseconds:500)
),
SizedBox(height:20),
ElevatedButton(
onPressed: () {
setState(() => isRed = !isRed);
},
child: const Text("Animate"),
),
],
),
);
}
}
initState
method to trigger the color change.build
method is called whenever setState
is invoked. For more precise control over state changes, consider using state management libraries.
Comments