Search code examples
flutterflutter-animation

custom repeating scaling animation


i am trying to achieved a scaling animation that starts from 0 to 1 and then alternates between 0.8 and 1. i copied the code from https://api.flutter.dev/flutter/widgets/ScaleTransition-class.html and tweaked the values but am unable to achieve my desired animation. the below code starts from 0.8 and animates to 1 and repeats. any ideas on how i can achieve the mentioned animation? tia

late final AnimationController _controller = AnimationController(
    value: 0,
    duration: const Duration(seconds: 2),
    vsync: this,
  )..repeat(min: 0.8, max: 1, reverse: true);
  late final Animation<double> _animation = CurvedAnimation(
    parent: _controller,
    curve: Curves.fastOutSlowIn,
  );

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

Solution

  • try this:

    late final AnimationController _controller = AnimationController(
            duration: const Duration(seconds: 2),
            value: 0,
            vsync: this,
          )..addStatusListener((status) async {
              if (status == AnimationStatus.completed) {
                _controller.animateBack(0.5);
                _controller.animateTo(1);
                _controller.repeat(min: 0.5, max: 1, reverse: true);
              }
            });
          late final Animation<double> _animation = CurvedAnimation(
            parent: _controller,
            curve: Curves.fastOutSlowIn,
          );
    

    Full sample:

    class _MainAppState extends State<MainApp> with TickerProviderStateMixin {
          late final AnimationController _controller = AnimationController(
            duration: const Duration(seconds: 2),
            value: 0,
            vsync: this,
          )..addStatusListener((status) async {
              if (status == AnimationStatus.completed) {
                _controller.animateBack(0.5);
                _controller.animateTo(1);
                _controller.repeat(min: 0.5, max: 1, reverse: true);
              }
            });
          late final Animation<double> _animation = CurvedAnimation(
            parent: _controller,
            curve: Curves.fastOutSlowIn,
          );
        
          @override
          void initState() {
            super.initState();
          }
        
          @override
          void dispose() {
            _controller.dispose();
            super.dispose();
          }
        
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              home: Scaffold(
                body: Center(
                  child: ScaleTransition(
                    scale: _animation,
                    child: const Padding(
                      padding: EdgeInsets.all(8.0),
                      child: FlutterLogo(size: 150.0),
                    ),
                  ),
                ),
              ),
            );
          }
        }