Flutter:动画师抛出异常

问题描述 投票:0回答:1

图标应闪烁 3 次,然后停止闪烁。眨眼停止后图标应该可见

运行正常,调度程序在停止后抛出异常

此异常是在调度程序回调的上下文中引发的。什么时候 调度程序回调已注册(与 抛出异常),这是堆栈:

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

  @override
  MyBlinkingIconState createState() => MyBlinkingIconState();
}

class MyBlinkingIconState extends State<MyBlinkingIcon>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  int _counter = 0;

  @override
  void initState() {
    _animationController =
    AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animationController.repeat(reverse: true);
    super.initState();
    _animationController.addStatusListener((status) {
      _counter++;
      if (_counter ==  4) {
        _animationController.stop();
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return _counter > 3 ?Assets.svgs.flame.svg() :FadeTransition(
      opacity: _animationController,
      child: Assets.svgs.flame.svg(),
    ) ;
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }
}
flutter mobile
1个回答
0
投票

这是正确的代码:

    import 'package:flutter/material.dart';

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

  @override
  MyBlinkingIconState createState() => MyBlinkingIconState();
}

class MyBlinkingIconState extends State<MyBlinkingIcon>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: const Duration(seconds: 1));

    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed || status == AnimationStatus.dismissed) {
        _counter++;
        if (_counter >= 3) {
          _animationController.stop();
        } else {
          _animationController.reverse();
        }
      } else if (status == AnimationStatus.reverse) {
        _animationController.forward();
      }
    });

    _animationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    return _counter >= 3
        ? Assets.svgs.flame.svg()
        : FadeTransition(
            opacity: _animationController,
            child: Assets.svgs.flame.svg(),
          );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.