ir2pid
ir2pid

Reputation: 6166

How to run an animation in loop

I'm shaking a widget using the below code, but the effect is once,

how do I keep it running in a loop at timed intervals. I believe it can be done by changing the key but it's a final and can't be changed.

import 'package:flutter/material.dart';

@immutable
class ShakeWidget extends StatelessWidget {
  final Duration duration;
  final double deltaX;
  final Widget child;
  final Curve curve;

  const ShakeWidget({
    Key key,
    this.duration = const Duration(milliseconds: 500),
    this.deltaX = 20,
    this.curve = Curves.bounceOut,
    this.child,
  }) : super(key: key);

  /// convert 0-1 to 0-1-0
  double shake(double animation) =>
      2 * (0.5 - (0.5 - curve.transform(animation)).abs());

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
      key: key,
      tween: Tween(begin: 0.0, end: 1.0),
      duration: duration,
      builder: (context, animation, child) => Transform.translate(
        offset: Offset(deltaX * shake(animation), 0),
        child: child,
      ),
      child: child,
    );
  }
}

Upvotes: 8

Views: 22780

Answers (4)

Kherel
Kherel

Reputation: 16225

You need to use AnimationController And call repeat when the controller is completed

enter image description here

import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp(
      home: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: SafeArea(
        child: ShakeWidget(
          child: Text('Hello world'),
        ),
      ),
    );
  }
}

class ShakeWidget extends StatefulWidget {
  const ShakeWidget({
    super.key,
    this.duration = const Duration(milliseconds: 500),
    this.deltaX = 20,
    this.curve = Curves.bounceOut,
    required this.child,
  });

  final Duration duration;
  final double deltaX;
  final Widget child;
  final Curve curve;

  @override
  State<ShakeWidget> createState() => _ShakeWidgetState();
}

class _ShakeWidgetState extends State<ShakeWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: widget.duration,
      vsync: this,
    )
      ..forward()
      ..addListener(() {
        if (controller.isCompleted) {
          controller.repeat();
        }
      });
  }

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

  /// convert 0-1 to 0-1-0
  double shake(double value) =>
      2 * (0.5 - (0.5 - widget.curve.transform(value)).abs());

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, child) => Transform.translate(
        offset: Offset(widget.deltaX * shake(controller.value), 0),
        child: child,
      ),
      child: widget.child,
    );
  }
}

Upvotes: 13

Robert Apikyan
Robert Apikyan

Reputation: 2127

Here is the repeating animation sample, from start → end then from end ← start

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: widget.duration);
    _animation = widget.tween.animate(
        CurvedAnimation(parent: _animationController, curve: Curves.easeIn));
    _animationController.forward();
    // The looping is done via listener.
    _animationController.addListener(() {
        if (_animationController.isCompleted) {
          _animationController.reverse();
        }
        if(_animationController.isDismissed){
          _animationController.forward();
        }
    });
  }

Don't forget to call _animationController.dispose() in the state's dispose() method.

Upvotes: 4

Code on the Rocks
Code on the Rocks

Reputation: 17854

The simple_animations package comes with the LoopAnimation widget which is meant for exactly this. This also means you don't have to create an AnimationController so the code's a lot cleaner.

LoopAnimation(
      builder: (context, child, double value) {
        return Transform.rotate(
          angle: pi * value,
          child: const Icon(Icons.notifications),
        );
      },
      duration: const Duration(seconds: 1),
      tween: Tween<double>(begin: 0, end: 2),

    );

If you want to run an animation forward and backward continuously to get a yo-yo effect, you can use the MirrorAnimation widget instead.

Upvotes: 3

HBS
HBS

Reputation: 670

Use an AnimationController, like so:

AnimationController(
  duration: const Duration(milliseconds: 300),
  vsync: this,
)..repeat();

Upvotes: 9

Related Questions