乐闻世界logo
搜索文章和话题

How to use lottie animation in flutter app?

1个答案

1

Using Lottie animations in Flutter applications is an excellent way to enhance user experience by implementing complex animation effects without significant performance overhead. The following are the steps to implement Lottie animations in Flutter:

1. Add Dependencies

First, you need to add the Lottie dependency to your Flutter project. Add the following lines to your pubspec.yaml file:

yaml
dependencies: flutter: sdk: flutter lottie: ^1.2.1

Then run flutter pub get to install the new dependency.

2. Add Lottie Files

You can download the required animation files from LottieFiles. After downloading, place the .json file into the assets folder of your Flutter project. Then, you need to declare these assets in pubspec.yaml:

yaml
flutter: assets: - assets/lottie_animation.json

3. Use Lottie Animations

In your Flutter code, you can use the Lottie widget to load and display Lottie animations. First, import the Lottie package:

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

Then, use the Lottie.asset method to load the animation:

dart
Lottie.asset('assets/lottie_animation.json')

4. Control the Animation

You can control animation playback, pause, and other behaviors using Lottie's controller:

dart
class _MyHomePageState extends State<MyHomePage> { late final AnimationController _controller; void initState() { super.initState(); _controller = AnimationController(vsync: this); } Widget build(BuildContext context) { return Lottie.asset( 'assets/lottie_animation.json', controller: _controller, onLoaded: (composition) { _controller ..duration = composition.duration ..forward(); }, ); } void dispose() { _controller.dispose(); super.dispose(); } }

In this example, the animation automatically starts playing when the widget loads and stops while releasing resources when the widget is removed.

By following these steps, you can effectively integrate Lottie animations into your Flutter applications to enhance visual appeal and user experience.

2024年8月9日 14:57 回复

你的答案