播放和暂停Flutter动画

10
2个回答

23

简短回答:

AnimationController _controller = ...;

// To stop animation
_controller.stop();

// To start from beginning
_controller.forward();

// To start from a point other than the very beginning.
_controller.forward(from: 0.8);


长答案:

我不知道那段代码,这是我的方法。你只需要使用Controller.reset()来停止动画并使用Controller.repeat()来开始它。

但是如果你只需要启动动画一次,请使用Controller.forward()Controller.reverse()

enter image description here

void main() => runApp(MaterialApp(home: Scaffold(body: HomePage())));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  bool _isPlaying = true;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      lowerBound: 0.3,
      duration: Duration(seconds: 3),
    )..repeat();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Animation")),
      body: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          _buildCircularContainer(200),
          _buildCircularContainer(250),
          _buildCircularContainer(300),
          Align(child: CircleAvatar(backgroundImage: AssetImage("assets/images/profile.png"), radius: 72)),
          Align(
            alignment: Alignment(0, 0.5),
            child: RaisedButton(
              child: Text(_isPlaying ? "STOP" : "START"),
              onPressed: () {
                if (_isPlaying) _controller.reset();
                else _controller.repeat();
                setState(() => _isPlaying = !_isPlaying);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCircularContainer(double radius) {
    return AnimatedBuilder(
      animation: CurvedAnimation(parent: _controller, curve: Curves.fastLinearToSlowEaseIn),
      builder: (context, child) {
        return Container(
          width: _controller.value * radius,
          height: _controller.value * radius,
          decoration: BoxDecoration(color: Colors.black54.withOpacity(1 - _controller.value), shape: BoxShape.circle),
        );
      },
    );
  }
}

8

当您直接访问动画控制器时,此代码片段将启动/停止动画,无论其离开的位置在哪里。

animationController.isAnimating
    ? animationController.stop()
    : animationController.forward();

这里的 .isAnimating 属性是布尔类型,当 animationController 正在进行动画时为 true。根据结果,.stop() / .forward() 分别停止/开始动画。


但是,如果你停止并前进,当它的值达到目标时,前进将不起作用。似乎动画不支持暂停和恢复,请参考此链接https://github.com/flutter/flutter/issues/3299。 - wjploop
1
如果您希望循环继续,请调用repeat()而不是forward()。 - Paul Sumpner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接