播放和暂停 Flutter 动画

Play & pause a Flutter animation

我试图向此页面添加一个按钮,该按钮将在后台播放(播放或暂停)波浪动画。 代码 link: https://github.com/apgapg/flutter_profile/blob/master/lib/page/intro_page.dart

我已经尝试了很多东西,但由于我仍然不喜欢 flutter 动画,所以我仍然没有结果。

提前致谢。

简答:

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()

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),
        );
      },
    );
  }
}

当您直接访问 AnimationController 时,此代码段将 start/stop 动画,无论它在哪里停止。

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

这里的 .isAnimating 属性 是 bool 类型,当 animationController 正在动画时为真。根据结果​​ .stop()/.forward() 将分别 stop/start 动画。