Search code examples
flutterflutter-layoutflutter-animation

Animation in Flutter: How to resize a Stack?


What's the right way to animate a change in size of a Stack widget?

The first idea was to wrap the Stack with a SizeTransition:

Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        SizeTransition(
          sizeFactor: _height, // Just a Tween<double>(begin: 200, end: 400)
          axis: Axis.vertical,
          axisAlignment: -1,
          child: Stack(
            children: [
              Positioned(
                bottom: 10,
                left: 10,
                child: Container(width: 50, height: 50, color: Colors.blue),
              ),
              Positioned(
                top: 10,
                right: 10,
                child: Container(width: 50, height: 50, color: Colors.green),
              ),
            ],
          ),
        ),
      ],
    );
  }

But running the snippet causes the following error:

'package:flutter/src/rendering/stack.dart': Failed assertion: line 588 pos 12: 'size.isFinite': is not true.

So, apparently, that's not the right way to do it. Questions now is: How do you animate resizing of a Stack?

Wrapping the Stack with a SizedBox would fix the error message, but then, how do you get the size from SizedTransition to set the proper size of a SizedBox?


Solution

  • You can use AnimatedContainer as parent of Stack widget by providing height or width one you like to change over time.

    AnimatedContainer(
      color: Colors.purple,
      duration: const Duration(milliseconds: 200),
      height: height,
      child: Stack(
        children: [
          Positioned(
            bottom: 10,
            left: 10,
            child: Container(width: 50, height: 50, color: Colors.blue),
          ),
          Positioned(
            top: 10,
            right: 10,
            child: Container(width: 50, height: 50, color: Colors.green),
          ),
        ],
      ),
    ),