【问题标题】:FadeTransition() widget is animated only once in flutter?FadeTransition() 小部件在颤动中只动画一次?
【发布时间】:2019-12-03 12:54:35
【问题描述】:
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"),
                  ),
                ],
              ),
            ),
          ),    
  ),
}
}

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

缺少什么,当切换FadeTransition() 时,小部件每次出现时都应该动画!

error 变量是使用Providers 从外部设置的,而无论error 发生变化,小部件都会重新构建,因此无需使用setState()

【问题讨论】:

    标签: animation flutter


    【解决方案1】:

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

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

    controller.forward(from: 0);
    // or
    controller.reset(); // stops the animation if in progress
    controller.forward();
    

    【讨论】:

    • 使用controller.forward(from: 0);时问题解决了,但我想知道其他动画在controller中不使用from也能正常工作,为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2019-07-03
    相关资源
    最近更新 更多