Home > Mobile >  Cannot restart a `TweenAnimationBuilder` animation
Cannot restart a `TweenAnimationBuilder` animation

Time:01-24

Cannot manage to restart my animation despite the setState().

My code as follows:


class SocOptimiserProgressIndicator extends StatefulWidget {
  @override
  State<SocOptimiserProgressIndicator> createState() =>
      _SocOptimiserProgressIndicatorState();
}

class _SocOptimiserProgressIndicatorState
    extends State<SocOptimiserProgressIndicator> {
  double _start = 0;

  @override
  Widget build(BuildContext context) {
    final size = 40.0;
    return TweenAnimationBuilder<double>(
        tween: Tween(begin: _start, end: 1.0),
        duration: Duration(seconds: 4),
        onEnd: () => setState(() {
              _start = 1 - _start;
            }),
        builder: (context, value, child) {
          // percentage to show in Center Text
          int percentage = (value * 100).ceil();
         
          // blah blah

CodePudding user response:

You can do this (notice the key as well, it might be a reason your widget is not rebuilt):

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  double _start = 0;
  double _end = 1;

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
      tween: Tween(begin: _start, end: _end),
      duration: const Duration(milliseconds: 2000),
      curve: Curves.linear,
      builder: (ctx, value, _) {
        print('value: $value');
        return FlutterLogo(
          key: ValueKey(value),
          size: 100 * value,
        );
      },
      onEnd: () {
        // restart the animation
        setState(() {
          var tmp = _start;
          _start = _end;
          _end = tmp;
        });
      },
    );
  }
}
  • Related