Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

Flutter how to use animatesized widgets when they are nested and I want to animated only…

  1. User

    Flutter how to use animatesized widgets when they are nested and I want to animated only one of them?

  2. Assistant

    When dealing with nested AnimatedSize widgets in Flutter, you can use the valueKey property 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 AnimatedSize widget that wraps a Column containing two children - a fixed-sized Text widget and another AnimatedSize widget that contains a Container. The valueKey property is set to 'animated_child' for the AnimatedSize widget that we want to animate.

    Whenever the _showBox variable changes (which could be triggered by some user action like a button press), the height of the animated_child widget changes, and only that widget is animated, and not the entire Column.