gpt4 book ai didi

flutter - Flutter Delayed动画代码错误:在AnimationController.dispose()之后调用了AnimationController.forward()

转载 作者:行者123 更新时间:2023-12-03 03:14:34 26 4
gpt4 key购买 nike

我在欢迎屏幕上实现了延迟动画,但是在Flutter App中出现以下错误。让我知道我的代码中是否有错误,可以纠正和解决此问题。
错误是:

E/flutter (11565): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)]Unhandled Exception:'package:flutter/src/animation/animation_controller.dart': Failedassertion: line 455 pos 7: '_ticker != null':AnimationController.forward() called afterAnimationController.dispose()


这是我的代码:
class DelayedAnimation extends StatefulWidget {
final Widget child;
final int delay;


DelayedAnimation({@required this.child, this.delay});

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

class _DelayedAnimationState extends State<DelayedAnimation>
with TickerProviderStateMixin {
AnimationController _controller;
Animation<Offset> _animOffset;

@override
void initState() {
super.initState();

_controller =
AnimationController(vsync: this, duration: Duration(milliseconds: 800));
final curve =
CurvedAnimation(curve: Curves.decelerate, parent: _controller);
_animOffset =
Tween<Offset>(begin: const Offset(0.0, 0.35), end: Offset.zero)
.animate(curve);

if (widget.delay == null) {
_controller.forward();
} else {
Timer(Duration(milliseconds: widget.delay), () {
_controller.forward();
});
}
}

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

@override
Widget build(BuildContext context) {
return FadeTransition(
child: SlideTransition(
position: _animOffset,
child: widget.child,
),
opacity: _controller,
);
}
}

最佳答案

当您使用TimerFuture.delayedAnimationController交互时,经常会出现此问题。这就是问题。可以说delay = 1000
以下代码告诉flutter,在1000毫秒内,在forward()小部件中的动画 Controller 上调用DelayedAnimation

Timer(Duration(milliseconds: widget.delay), () {
_controller.forward();
});
但是,在此之前,您的 DelayedAnimation小部件已被处置(例如,如果用户移动到其他屏幕,则会发生这种情况)
这意味着当执行 Timer时,它将在已处置的 Controller 上调用 forward()(因为 DelayedAnimation已处置)
有一些解决方案。
  • 在向前调用之前检查mounted属性:
  • Timer(
    Duration(
    milliseconds: widget.delay
    ),
    () {
    if(mounted) {
    _controller.forward();
    }
    }
    );
    或2.在创建计时器时将其存储:
    _timer = Timer(
    Duration(
    milliseconds: widget.delay
    ),
    () {
    _controller.forward();
    }
    );
    然后在处置时将其取消:
    @override
    void dispose() {
    super.dispose();
    _controller.dispose();
    _timer?.cancel();
    }

    关于flutter - Flutter Delayed动画代码错误:在AnimationController.dispose()之后调用了AnimationController.forward(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62726872/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com