FadeTransition() 小部件在颤动中仅动画一次?

rah*_*aha 4 animation flutter

class pin extends StatefulWidget {
@override
_PinState createState() => _PinState();
}

class _PinState extends State<pin> with TickerProviderStateMixin {
AnimationController _controller;
Animation<double> _animation;
bool error = false;


@override
void initState() {
  super.initState();
  this._controller = AnimationController(
      duration: const Duration(milliseconds: 1000), vsync: this);
  this._animation =
      Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
    parent: _controller,
    curve: Curves.easeIn,
  ));
}

@override
Widget build(BuildContext context) {
  if(this.error) {
    this.error = false;
    _controller.forward();
  }
  return Container(
    child: if (this.error)
            Container(
            child: FadeTransition(
              opacity: _animation,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Image.asset("assets/images/sad_face.png"),
                  ),
                ],
              ),
            ),
          ),    
  ),
}
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,FadeTransition()当应用程序首次启动时,小部件是动画的。并且 的可见性FadeTransition()error变量切换。但是下次FadeTransition()小部件可见时它没有动画?

缺少什么,切换FadeTransition()小部件时应该在每次出现时进行动画处理!

error变量是从外部使用设置的Providers,无论在何处error更改小部件都会重新构建,因此无需使用setState()

小智 8

我注意到的一件事error是总是错误的。没有代码可以将其变为真,并且有两个地方将其设置为假。其中之一取决于它是否为真的(它永远不会是因为error = true不存在)

话虽如此,如果您想让动画再次运行,无论在何处切换此属性(通常在按钮的onTap方法中),您都必须调用 setState。在 setState 中,您可以使用

controller.forward(from: 0);
// or
controller.reset(); // stops the animation if in progress
controller.forward();
Run Code Online (Sandbox Code Playgroud)

  • 使用“controller.forward(from: 0);”时问题得到解决,但我想知道其他动画在“controller”中不使用“from”时也能正常工作,为什么? (2认同)