flutterheightdurationanimatedcontainer

How to make an AnimatedContainer change height after intial widget build, instead of on Button Click


                Expanded(
                  flex: 1,
                  child: Padding(
                    padding: const EdgeInsets.only(bottom: 3.0, right: 1),
                    child: AnimatedContainer(
                      duration: Duration(seconds: 1),
                      height: voteCountList[0],
                      decoration: BoxDecoration(
                        color: ColorChooser.graphColors[int.parse(optionsList[0]['color'])],
                        borderRadius: BorderRadius.all(Radius.circular(2))
                      ),
                    ),
                  ),
                ),

As seen in my code snippet the height of the Animated Container is voteCountList[0], this works fine if the value is updated. However when the widget is initially build there is no animation and the height of the container is instantly = voteCountList[0]. I would like to implement the AnimatedContainer such that the height of the container is seen to animate from 0 to voteCountList[0]. This height needs to animated on build.


Solution

  • If you don't want to use an AnimatedBuilder or create your own Animation controller one way to do it with the Animatedcontainer would be

    class MyWidget extends StatelessWidget {
      Future<double> get _height => Future<double>.value(200);
    
      @override
      Widget build(BuildContext context) {
        return Padding(
            padding: const EdgeInsets.only(bottom: 3.0, right: 1),
            child: FutureBuilder<double>(
              future: _height,
              initialData: 0.0,
              builder: (context, snapshot) {
                return AnimatedContainer(
                  duration: Duration(seconds: 1),
                  width: 200,
                  height: snapshot.data, //voteCountList[0],
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.all(Radius.circular(2))),
                );
            }
          )
        );
      }
    }
    

    You start a future with an initial value of 0.0 and after a tick the futures resolve (it's a value you already had, you only transformed it to a future to make him think it will be ready in a tick) and the animation will start from 0 to the resolved future voteCountList[0]