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

How to show and hide the Lottie animation in Flutter

1个答案

1

In Flutter, to show and hide Lottie animations, the basic approach is to use a boolean variable to control the visibility of the animation component (via the Visibility widget or conditional rendering). Below, I will explain how to achieve this effect with an example code.

Overview of Steps:

  1. Add the Lottie package: First, add the Lottie Flutter library to the pubspec.yaml file.

  2. Create a boolean state variable: This variable controls whether the animation is visible.

  3. Use the Visibility widget: Control the visibility of the Lottie animation using this widget.

  4. Control animation visibility: Change the value of the boolean variable via a button to indirectly control the animation's visibility.

Example Code:

First, ensure that you have added the lottie package to your Flutter project's pubspec.yaml:

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

Then, you can create a simple Flutter application to achieve this functionality:

dart
import 'package:flutter/material.dart'; import 'package:lottie/lottie.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { bool _isAnimationVisible = true; Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Lottie Animation Demo'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[" Visibility( visible: _isAnimationVisible, child: Lottie.asset('assets/lottie_animation.json'), ), ElevatedButton( onPressed: () { setState(() { _isAnimationVisible = !_isAnimationVisible; }); }, child: Text(_isAnimationVisible ? 'Hide Animation' : 'Show Animation'), ) ], ), ), ), ); } }

Explanation:

Here, Lottie.asset('assets/lottie_animation.json') is used to load the animation. Ensure that you have a Lottie file named lottie_animation.json in your assets folder and that the assets path is correctly configured in pubspec.yaml.

The Visibility widget shows or hides the animation based on the boolean value of _isAnimationVisible.

When the user clicks the button, the value of _isAnimationVisible flips, triggering a rebuild of the interface and updating the animation's visibility state.

This example demonstrates how to control the visibility of Lottie animations in a Flutter application based on user interaction.

2024年8月9日 15:44 回复

你的答案