Consider this Flutter widget that uses AnimatedContainer. What will you see after tapping the container?
class MyWidget extends StatefulWidget { @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { bool selected = false; @override Widget build(BuildContext context) { return GestureDetector( onTap: () => setState(() => selected = !selected), child: AnimatedContainer( width: selected ? 200 : 100, height: selected ? 100 : 200, color: selected ? Colors.blue : Colors.red, duration: Duration(seconds: 1), curve: Curves.easeInOut, ), ); } }
AnimatedContainer automatically animates changes to its properties over the given duration.
AnimatedContainer animates changes to its width, height, and color smoothly over the specified duration when the state changes.
Look at this Flutter widget using AnimatedOpacity. What will the user see when the button is pressed?
class FadeWidget extends StatefulWidget { @override State<FadeWidget> createState() => _FadeWidgetState(); } class _FadeWidgetState extends State<FadeWidget> { bool visible = true; @override Widget build(BuildContext context) { return Column( children: [ AnimatedOpacity( opacity: visible ? 1.0 : 0.0, duration: Duration(milliseconds: 500), child: Container( width: 100, height: 100, color: Colors.green, ), ), ElevatedButton( onPressed: () => setState(() => visible = !visible), child: Text('Toggle'), ), ], ); } }
AnimatedOpacity animates the transparency of its child widget.
AnimatedOpacity smoothly changes the opacity from 1.0 (fully visible) to 0.0 (invisible) over the given duration.
In Flutter, when you call setState to change properties of an AnimatedContainer, why does it animate the change instead of instantly updating?
Think about how implicit animations work in Flutter.
AnimatedContainer detects changes in its properties and animates smoothly from the old to the new value automatically.
Choose the correct Flutter code snippet that fades out a widget smoothly over 2 seconds using AnimatedOpacity.
Duration must be created with Duration() and seconds as a named parameter.
Option A correctly uses Duration(seconds: 2) and opacity as a double 0.0.
Given this Flutter code, why does the container jump instantly instead of animating?
class MyWidget extends StatefulWidget {
@override
State createState() => _MyWidgetState();
}
class _MyWidgetState extends State {
bool selected = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => selected = !selected,
child: AnimatedContainer(
width: selected ? 200 : 100,
height: selected ? 100 : 200,
color: selected ? Colors.blue : Colors.red,
duration: Duration(seconds: 1),
),
);
}
} Remember what triggers a widget rebuild in Flutter.
Without calling setState(), Flutter does not know the state changed and does not rebuild the widget, so no animation occurs.