Search code examples
flutterdartanimationflutter-animation

how to automatically animate without a button trigger


I am creating an animation to move the Icon vertically. I would like to trigger the animation automatically (at the time the Widget is generated) rather than by pressing a button or similar means. However, I don't know how to do it, so I'm asking here.

This is the code I have created up to this point. In this code, the animation does not play.


class UpDown extends StatefulWidget {
  const UpDown({super.key});

  @override
  UpDownState createState() {
    return UpDownState();
  }
}

class UpDownState extends State<UpDown> with SingleTickerProviderStateMixin {
  bool flag = true;

  late AnimationController controller;

  @override
  Widget build(BuildContext context) {
    Future<void> up() async {
      flag = true;
      await Future<void>.delayed(const Duration(milliseconds: 500));
      setState(() {});
    }

    Future<void> down() async {
      flag = false;
      await Future<void>.delayed(const Duration(milliseconds: 500));
      setState(() {});
    }

    return AnimatedAlign(
      alignment: flag ? Alignment.topCenter : Alignment.bottomCenter,
      duration: const Duration(milliseconds: 500),
      curve: Curves.fastOutSlowIn,
      onEnd: () => flag ? down() : up(),
      child: const Icon(
        CupertinoIcons.hand_point_left_fill,
        color: Color.fromARGB(255, 235, 235, 235),
      ),
    );
  }
}

Solution

  • You can trigger the animation in the initState() function of your state so that it will start when the widget is built