xvrh / lottie-flutter

Render After Effects animations natively on Flutter. This package is a pure Dart implementation of a Lottie player.
https://pub.dev/packages/lottie
MIT License
1.15k stars 197 forks source link

How to achieve accelerated playback? #287

Open FengZi-lv opened 1 year ago

FengZi-lv commented 1 year ago

I have an animation, I want to speed up his playback when needed, is there any way to achieve it? Thanks.

xvrh commented 1 year ago

By providing a custom AnimationController you can control precisely your playback.

Here is an example to speed up x5 (in the onLoaded callback, we get the duration of the animation and divide it by 5 for the custom AnimationController).

import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            Lottie.asset(
              'assets/AndroidWave.json',
              controller: _controller,
              frameRate: FrameRate.max,
              onLoaded: (composition) {
                // Configure the AnimationController with the duration of the
                // Lottie file and start the animation.
                _controller
                  ..duration = Duration(
                      milliseconds:
                          (composition.duration.inMilliseconds / 5).round())
                  ..repeat();
              },
            ),
          ],
        ),
      ),
    );
  }
}

Hope this helps