Flutter how to use animatesized widgets when they are nested and I want to animated only…
- User
Flutter how to use animatesized widgets when they are nested and I want to animated only one of them?
- Assistant
When dealing with nested AnimatedSize widgets in Flutter, you can use the
valueKeyproperty to specify a unique key for the child widget that you want to animate. This will ensure that only that particular widget is animated when its size changes.Here is an example code snippet:
AnimatedSize( duration: Duration(milliseconds: 500), curve: Curves.easeInOut, child: Column( children: [ Text( 'Fixed Size', style: TextStyle(fontSize: 24), ), AnimatedSize( duration: Duration(milliseconds: 500), curve: Curves.easeInOut, vsync: this, key: ValueKey('animated_child'), child: Container( width: screenWidth * 0.8, height: _showBox ? 200.0 : 0.0, // change height based on some condition color: Colors.blue, ), ), RaisedButton( child: Text('Toggle Box'), onPressed: () { setState(() { _showBox = !_showBox; }); }, ), ], ), ),In this example, we have a top-level
AnimatedSizewidget that wraps aColumncontaining two children - a fixed-sizedTextwidget and anotherAnimatedSizewidget that contains aContainer. ThevalueKeyproperty is set to'animated_child'for theAnimatedSizewidget that we want to animate.Whenever the
_showBoxvariable changes (which could be triggered by some user action like a button press), the height of theanimated_childwidget changes, and only that widget is animated, and not the entireColumn.