Search code examples
flutterflutter-animation

AnimatedSwitcher not animating


Can someone please help understand why this simple animated swticher doesnt work?

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool _showFrontSide = true;

  @override
  Widget build(BuildContext context) {

    final face = _showFrontSide ?
      Container(key: const ValueKey(true), child: Text("Front")) :
      Container(key: const ValueKey(false), child: Text("Back"));

    return GestureDetector(
        onTap: () => {
          setState(() {
            _showFrontSide = !_showFrontSide;
          })
        },
        child: AnimatedSwitcher(
          duration: const Duration(microseconds: 1500),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return ScaleTransition(scale: animation, child: child);
          },
          child: face,
        ));
  }
}

Full example can be seen here: https://dartpad.dev/?id=d1e94dc9e6b1fe901f6bfe6a1149be64

Almost all discussions point to setting a unique key on the children for animateswitcher to detect a change, and trigger animating. I dont understand why it doesnt work in this case.


Solution

  • It works, but the Duration is too short to be visible (microseconds are not visible to our eyes). Try to set milliseconds instead of microseconds and the animation will become visible.

    AnimatedSwitcher(
      duration: const Duration(milliseconds: 500),
      ...
    ),