I want to control the gif animation by clicking the button i.e., If I pressed the 'click me' button animation start and again pressing animation should stop. I am taking reference for this question How to display an animated picture in Flutter?
I don't want to split the gif images into frames, I have to use only one gif image and control only that. Here is my code.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State createState() => new MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
AnimationController _controller;
Animation<int> _animation;
@override
void initState() {
_controller = new AnimationController(
vsync: this, duration: const Duration(seconds: 3))
..stop();
_animation = new IntTween(begin: 0, end: 7).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return new Scaffold(
body: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new AnimatedBuilder(
animation: _animation,
builder: (BuildContext context, Widget child) {
String frame = _animation.value.toString().padLeft(0, '0');
return new Image.asset(
'assets/lips.gif',
gaplessPlayback: true,
);
},
),
new RaisedButton(
child: new Text('click me'),
onPressed: () {
if (_controller.isAnimating) {
_controller.stop();
} else {
_controller.repeat();
}
},
),
],
),
);
}
}
Currently, Flutter supports playing GIF
files using Image
widget.
But there is still no easy way to control (e.g pause and play) the GIF
files. When it comes to controlling it, one of the workaround is to use a package. Lottie for Flutter could be use to implement this behavior.
Workaround :
- Convert your gif to mp4 (Gif to mp4)
- Convert mp4 to Lottie json (Mp4 to Json)
- Upload your Lottie json to
lottiefiles.com
or add to yourassets
folder- Use Lottie package to load your animation
Try to check this tutorial from Medium: "Explore Lottie Animation In Flutter".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With