Do you want your app animations to look just right and feel consistent across different screens? Creating a custom animation widget can help you achieve this easily.
Why Create Custom Animations?
Building custom animation effects and packaging them into a reusable widget means you only define the animation once. Then, you can use it in many places throughout your app, ensuring a consistent look and feel without repeating code.
Using flutter_animate
The flutter_animate
package makes creating complex animation sequences simple. You can chain different effects like fading, moving, and scaling together.
Building Your Custom Animation Widget
You can create a simple StatelessWidget
that wraps its child with the Animate
widget from the package.
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
class MoveFadeAnim extends StatelessWidget {
final int? delayInMs;
final Widget child;
const MoveFadeAnim({
super.key,
required this.child,
this.delayInMs,
});
Widget build(BuildContext context) {
return Animate(
effects: [
// Add your list of effects here
],
child: child,
);
}
}
Adding Effects
Inside the effects
list, you add the animations you want. For example, a fade effect and a move effect:
effects: [
FadeEffect(
delay: Duration(milliseconds: delayInMs ?? 0),
duration: const Duration(milliseconds: 300),
curve: Curves.easeIn,
),
MoveEffect(
delay: Duration(milliseconds: delayInMs ?? 0),
duration: const Duration(milliseconds: 450),
curve: Curves.easeOut,
begin: const Offset(0, 50),
end: Offset.zero,
),
],
Staggered Animations
Notice the delayInMs
property. By adding this to your custom widget and using it in the delay
property of each effect, you can easily create staggered animations when showing a list of items. Just pass a different delay for each item.
Reusing Your Animation
Now, you can use your MoveFadeAnim
widget anywhere you want this specific animation sequence to play. You just wrap the widget you want to animate with MoveFadeAnim
and optionally provide a delay.
// Example usage in a list builder
return MoveFadeAnim(
delayInMs: index * 150 + 50, // Calculate delay for staggered effect
child: MenuCard(
height: 130,
// ... other properties
),
);
By doing this, you ensure that every time you use MoveFadeAnim
, the exact same fade and move effects play, creating a consistent and professional look for your app.