I need to animate the size of a widget when the widget changes from an expanded widget to a normal widget inside a Flex. I also want the other children of the flex to animate to their new positions.
The current code doesn't work because it doesn't animate a jumps between the sizes:
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool expand = false;
void _expandToggle() {
setState(() => expand = !expand);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Whether the child below is expanded:',
),
Expanded(
flex: expand ? 1 : 0,
child: AnimatedSize(
duration: const Duration(seconds: 3),
child: ColoredBox(
color: Colors.yellow,
child: Text(
'$expand',
style: Theme.of(context).textTheme.headlineMedium,
),
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _expandToggle,
child: const Icon(Icons.add),
),
);
}
}
I think the reason why it doesn't animate is because ideally the Expanded should be wrapped in the AnimatedSize. But of course Flutter wouldn't allow that.