Triggering Animations in Flutter
Ever wondered how to make an animation play in your Flutter app when a specific setting or value changes in your widget? It's a common task, especially when dealing with state changes.
The Key Function: didUpdateWidget
In Flutter, StatefulWidgets have a special function called didUpdateWidget
. This function is automatically called every time the widget is rebuilt with new data. It's the perfect spot to check if a property you care about has changed.
How it Works
The didUpdateWidget
method gives you access to the oldWidget
. This means you can compare the properties of the current widget (widget
) with the properties of the widget before it was updated (oldWidget
).
Simple Property Check
Let's say your widget has a bool
property called isUploading
, and you want to start an animation when it changes from false
to true
.
void didUpdateWidget(covariant UploadedAvatarAnimation oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.isUploading && !oldWidget.isUploading) {
// Start your animation here
_controller.forward(from: 0);
}
}
This works well for single properties. However, be careful if your widget has many properties. didUpdateWidget
fires whenever any property changes, so your check needs to be specific.
A Sexier Dart 3 Pattern
For handling changes between different states or multiple properties, the new Dart 3 pattern using switch
on a tuple can be very clean.
void didUpdateWidget(covariant UploadedAvatarAnimation oldWidget) {
super.didUpdateWidget(oldWidget);
final (wasUploading, isUploading) = (
oldWidget.isUploading,
widget.isUploading
);
switch ((wasUploading, isUploading)) {
case (false, true):
// Transition from not uploading to uploading
_controller.forward(from: 0);
break;
case (true, false):
// Transition from uploading to not uploading
_controller.reverse(from: 1);
break;
default:
// No change in upload status or other transitions
break;
}
}
This pattern allows you to define specific actions for specific state transitions (e.g., false
to true
, true
to false
).
Conclusion
Using didUpdateWidget
is the standard way to react to property changes in a StatefulWidget and trigger actions like starting or reversing animations. Choose the simple if
check for single properties or the Dart 3 switch
pattern for more complex state transitions.