颤动:从当前对象位置重新启动SlideAnimation

时间:2017-08-01 11:12:38

标签: animation dart flutter

我在每次点击屏幕时触发的对象上都有一个SlideAnimation。该对象只是向上滑动atm,但当我再次点击屏幕时,动画再次从对象的原始位置开始。如何捕捉对象在上一个动画中结束的位置并从那里开始动画?
我有以下用于创建SlideTransition的代码:

        new SlideTransition(
          child: new Container(
            child: char,
          ),
          position: _characterPosition,
        )

这个实际动画的代码:

_characterPosition = new FractionalOffsetTween(
  begin: const FractionalOffset(0.0, 0.0),
  end: const FractionalOffset(0.0, -0.2),
).animate(new CurvedAnimation(
  parent: _characterAnimationController,
  curve: Curves.easeOut,
  )
);

1 个答案:

答案 0 :(得分:3)

在最简单的情况下,您可以使用_characterAnimationControllerAnimationController有两种相关方法stopforward。验证当前动画的状态并调用所需的方法:

void _onTap() {
    if (_characterAnimationController.isAnimating) {
      _characterAnimationController.stop(canceled: false);
    } else {
      _characterAnimationController.forward();
    }
}

要在完成后扩展动画,您可以通过_characterAnimationController(或创建新的)重置value状态并更新位置。完整的例子:

class Home extends StatefulWidget {
  @override
  State createState() => new _HomeState();
}

class _HomeState extends State<Home> with TickerProviderStateMixin {
  Animation _characterPosition;
  AnimationController _characterAnimationController;
  FractionalOffset _beginOffset;
  FractionalOffset _endOffset;
  FractionalOffset _animationOffset;

  void _restartAnimation() {
    _characterAnimationController.value = 0.0;
    _beginOffset = _endOffset;
    _endOffset = _endOffset + _animationOffset;

    setState(() {
      _characterPosition = _generateCharacterPosition();
    });

    _characterAnimationController.forward();
  }

  @override
  void initState() {
    _animationOffset = const FractionalOffset(0.0, 0.15);
    _beginOffset = const FractionalOffset(0.0, 0.0);
    _endOffset = _animationOffset;

    _characterAnimationController = new AnimationController(
        duration: new Duration(seconds: 5), vsync: this);
    _characterPosition = _generateCharacterPosition();
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      child: new InkWell(
        child: new SlideTransition(
          child: new Container(
            child: new Text("Hello"),
          ),
          position: _characterPosition,
        ),
        onTap: _onTap,
      ),
    );
  }

  void _onTap() {
    if (_characterAnimationController.isAnimating) {
      _characterAnimationController.stop(canceled: false);
    } else if (_characterAnimationController.status ==
        AnimationStatus.completed) {
      _restartAnimation();
    } else {
      _characterAnimationController.forward();
    }
  }

  Animation _generateCharacterPosition() => new FractionalOffsetTween(
        begin: _beginOffset,
        end: _endOffset,
      )
          .animate(new CurvedAnimation(
        parent: _characterAnimationController,
        curve: Curves.easeOut,
      ));
}