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:
-
Add the Lottie package: First, add the Lottie Flutter library to the
pubspec.yamlfile. -
Create a boolean state variable: This variable controls whether the animation is visible.
-
Use the Visibility widget: Control the visibility of the Lottie animation using this widget.
-
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:
yamldependencies: flutter: sdk: flutter lottie: ^1.2.1
Then, you can create a simple Flutter application to achieve this functionality:
dartimport '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.