Sub topic 5
AnimatedOpacity, AnimatedAlign and other implicit widgets
This chapter assumes you know AnimatedContainer, the duration and curve parameters, and setState in a StatefulWidget. Here you will meet the rest of the built-in implicit widgets, learn which property each one animates, and learn the rules that make them behave as expected.
One idea, many widgets
AnimatedContainer animates many properties at once. Often you need only one property, such as opacity or alignment. Flutter ships a dedicated implicit widget for most of them. They all work the same way:
- You pass a target value and a
duration. - When the parent rebuilds with a different value, the widget animates from the current value to the new one.
- The widget owns its controller and ticker and disposes them for you.
Most of these widgets extend ImplicitlyAnimatedWidget. Its state creates the controller and tweens for you, so you never write them.
The common widgets
| Widget | Animates | Target parameter | Notes |
|---|---|---|---|
| `AnimatedOpacity` | Transparency | `opacity` (0.0 to 1.0) | The child keeps its layout space and still receives taps at 0.0. |
| `AnimatedAlign` | Position inside the parent | `alignment` | Expands to fill the available space, like `Align`. |
| `AnimatedPadding` | Space around the child | `padding` | Changes layout, so neighbors move. |
| `AnimatedPositioned` | Offsets inside a `Stack` | `left`, `top`, `right`, `bottom`, `width`, `height` | Must be a direct child of a `Stack`. |
| `AnimatedScale` | Size by a factor | `scale` | Paint-only. Layout size does not change. |
| `AnimatedRotation` | Angle in full turns | `turns` | `1.0` is one full rotation. Paint-only. |
| `AnimatedSlide` | Offset as a fraction of the child's size | `offset` | Paint-only. |
| `AnimatedDefaultTextStyle` | Text style | `style` | Affects descendant `Text` widgets. |
AnimatedScale, AnimatedRotation and AnimatedSlide apply a transform. They do not trigger layout on every frame, which makes them cheaper than AnimatedPadding or AnimatedContainer with a changing size.
Combining several in one screen
Each widget animates independently. You can nest them and drive them all from one boolean.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(body: Center(child: ImplicitGallery())),
),
);
class ImplicitGallery extends StatefulWidget {
const ImplicitGallery({super.key});
@override
State<ImplicitGallery> createState() => _ImplicitGalleryState();
}
class _ImplicitGalleryState extends State<ImplicitGallery> {
bool _active = false;
@override
Widget build(BuildContext context) {
const duration = Duration(milliseconds: 500);
return Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 300,
height: 200,
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
),
child: AnimatedAlign(
duration: duration,
curve: Curves.easeInOut,
alignment:
_active ? Alignment.bottomRight : Alignment.topLeft,
child: AnimatedOpacity(
duration: duration,
opacity: _active ? 1.0 : 0.3,
child: AnimatedScale(
duration: duration,
scale: _active ? 1.0 : 0.6,
child: const FlutterLogo(size: 60),
),
),
),
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => setState(() => _active = !_active),
child: Text(_active ? 'Reset' : 'Move'),
),
],
);
}
}One setState changes _active. Three widgets receive new targets and each animates its own property over 500 ms. The outer AnimatedAlign moves the logo. The inner widgets fade and grow it as it travels.
AnimatedPositioned and its Stack requirement
AnimatedPositioned is the animated form of Positioned. Like Positioned, it only works as a direct child of a Stack. Wrapping it in another widget throws a "Incorrect use of ParentDataWidget" error.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(home: Scaffold(body: Center(child: SlidingChip()))),
);
class SlidingChip extends StatefulWidget {
const SlidingChip({super.key});
@override
State<SlidingChip> createState() => _SlidingChipState();
}
class _SlidingChipState extends State<SlidingChip> {
bool _right = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _right = !_right),
child: SizedBox(
width: 300,
height: 80,
child: Stack(
children: [
AnimatedPositioned(
duration: const Duration(milliseconds: 400),
curve: Curves.fastOutSlowIn,
left: _right ? 220 : 0,
top: 20,
width: 80,
height: 40,
child: const DecoratedBox(
decoration: BoxDecoration(
color: Colors.teal,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
),
),
],
),
),
);
}
}Give AnimatedPositioned a consistent set of constraints. Here left, width and top, height fully determine the box. Animating between a value and null does not interpolate.
Rules shared by all implicit widgets
The first build does not animate
The widget draws its initial target immediately. Animation starts only when a rebuild supplies a different value. To animate on entry, start from one value and change it after the first frame, for example with WidgetsBinding.instance.addPostFrameCallback. If entry animation is your main need, TweenAnimationBuilder or an explicit controller is cleaner.
Retargeting mid-flight
If the target changes while an animation runs, the widget does not jump. It starts a new animation from the current value to the new target. Rapid taps therefore produce smooth reversals.
Completion callback
Every ImplicitlyAnimatedWidget accepts onEnd. It fires when an animation reaches its target. This is the implicit way to chain a second step.
AnimatedOpacity(
duration: const Duration(milliseconds: 300),
opacity: _visible ? 1.0 : 0.0,
onEnd: () {
if (!_visible) setState(() => _removed = true);
},
child: const Text('Notice'),
)Use it, for instance, to drop a widget from the tree after it has faded out.
Widgets that look implicit but are not
Several widgets named Animated... do not extend ImplicitlyAnimatedWidget. They still hide the controller from you.
AnimatedSwitchercross-fades between an old and new child. Flutter detects a change by comparing widget type andkey. Give each state a different key, such asValueKey(_count), or nothing animates.AnimatedCrossFadefades and resizes between two named children, selected bycrossFadeState.AnimatedSizeanimates its own size when its child's size changes. It has no target parameter.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(home: Scaffold(body: Center(child: Counter()))),
);
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
transitionBuilder: (child, animation) =>
ScaleTransition(scale: animation, child: child),
child: Text(
'$_count',
key: ValueKey<int>(_count),
style: const TextStyle(fontSize: 48),
),
),
TextButton(
onPressed: () => setState(() => _count++),
child: const Text('Add'),
),
],
);
}
}If you removed the key, both texts would be of type Text with no key, so AnimatedSwitcher would treat them as the same child and show no animation.
Common mistakes
- Putting
AnimatedPositionedoutside aStack. It needs aStackas its direct parent. - Forgetting that
AnimatedAlignfills its parent. Without bounded constraints, it expands as far as it can. Give it a sized parent. - Animating layout when a transform would do. Prefer
AnimatedSlideorAnimatedScaleoverAnimatedPaddingfor purely visual motion. - Expecting a
durationof zero to animate. It applies the new value at once. - Expecting the animation to run after a hot reload. Changing the code does not change the target, so nothing animates until the state changes.
Exercise
A "Dismiss" button is wrapped in AnimatedOpacity(opacity: _show ? 1.0 : 0.0, ...). After _show becomes false, users can still tap the invisible button. Give two ways to fix this.
Show answer
Wrap the button in IgnorePointer(ignoring: !_show) so it ignores taps while transparent. Alternatively, set onEnd on the AnimatedOpacity to call setState and remove the button from the tree once the fade finishes. AnimatedOpacity only changes paint, so the child stays in the tree and still receives hit tests at 0.0.
Exercise
You use AnimatedSwitcher to animate a changing label, but the text swaps with no animation. The child is Text(label) with no key. What is wrong and what is the fix?
Show answer
AnimatedSwitcher decides that the child changed by comparing the widget type and key. Both widgets are Text with a null key, so it treats them as the same child. Add a distinct key, for example key: ValueKey<String>(label).