Search code examples
flutteranimationanimatedcontainer

Icons still showing even if it's parent widget's height is zero in Flutter


I have an AnimatedContainer and as it's child, I have a Row containing a Text and an IconButton. After clicking some button, I am toggling the height of the Container between 0 and 100. When the Container height is zero, the IconButton is still visible (not the Text) and not clickable. enter image description here

enter image description here

 Widget _myAnimatedContainer() {
    return AnimatedContainer(
      curve: Curves.easeOut,
      alignment: Alignment.center,
      duration: Duration(milliseconds: 300),
      height: height,
      color: Colors.green,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          Text(
            'Animated Container',
            style: TextStyle(fontSize: 20),
            overflow: TextOverflow.ellipsis,
          ),
          IconButton(icon: Icon(Icons.favorite_border), onPressed: () {},)
        ],
      ),
    );
  }

class _AnimatedContainerExampleState extends State<AnimatedContainerExample> {
  double height = 100;
  bool isExpanded = false;
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            _myAnimatedContainer(),
            SizedBox(height: 20,),
            RaisedButton(
              child: Text('Expand'),
              onPressed: () {
                setState(() {
                  isExpanded = !isExpanded;
                  height = isExpanded ? 100 : 0;
                });
              },
            ),
          ],
        ),
    );
  }

Please suggest how to solve this issue.


Solution

  • Add the if condition:

    if (height > 0)
         IconButton(icon: Icon(Icons.favorite_border), onPressed: () {},)
    

    You might want to use a different value from 0 (like 10) to remove the icon