Play & pause a Flutter animation
I wasn't aware of that code, here is how I did. All you need is Controller.reset()
to stop the animation and Controller.repeat()
to start it.
However if you need to start the animation just once, use Controller.forward()
and 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), ); }, ); }}
When you directly have access to the AnimationController this snippet will start/stop the animation, wherever it left off.
animationController.isAnimating ? animationController.stop() : animationController.forward();
Here the .isAnimating
property is of type bool and is true when the animationController is animating at the moment. Depending on the result .stop()
/.forward()
will stop/start the animation respectively.