I coded a simple Lottie animation state manager. From a pool of lottie-json files, each containing also a probability to play, I select one and set the _index to play that file.
However, if randomly the same file will that played before will be played again, the loop just stops and I have to restart... I depict a minimal example of my code here:
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
final Random rnd = Random();
int _index = 0;
late BechtoAnimation _animation;
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this)
..addStatusListener((status) {
if(status == AnimationStatus.completed){
setState(() {
int i = 0;
double p = rnd.nextDouble();
double cumulativeProbability = 0.0;
for(AnimationLoop animationLoop in _animation.loop){
cumulativeProbability += animationLoop.probability;
if (p <= cumulativeProbability) {
_index = i;
break;
}
i++;
}
});
}
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext buildContext) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
BlocBuilder<MyCubit, MyState>(
builder: (context, state) {
if(state is AnimationLoadedFailure){
return Text(state.toString(), style: const TextStyle(color: Colors.blueGrey));
}else if(state is AnimationLoadedSuccess){
_animation = state.animation;
return SizedBox(
width: 200,
height: 200,
child: Lottie.asset(
state.animation.loop.elementAt(_index).fileName,
width: 200,
height: 200,
fit: BoxFit.fill,
controller: _controller,
onLoaded: (composition){
_controller.duration = composition.duration;
_controller.reset();
_controller.forward();
}
),
);
}else{
return Text(state.toString(), style: const TextStyle(color: Colors.blueGrey));
}
}
)
],
),
));
}
}
As you can see, I select the new animation when the old one is finished via the StatusListener. However, when its the same, everything just stops... Any idea?
Flutter version is: 3.3.0 and my Dart version is 2.18.0