flutter - Flutter:如何显示和隐藏 Lottie 动画
问题描述
我已经成功地展示了 Lottie,如下所示:
但问题是,如何通过按钮触发显示和隐藏 Lottie?例如,Lottie 没有显示,但是当我点击 时Show Lottie button
,Lottie 会显示,而当我点击 时Hide Lottie button
,Lottie 会隐藏。
这是我的完整代码:
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Lottie Flutter'),
),
body: Container(
width: double.infinity,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
SizedBox(
width: 50,
height: 50,
child: Lottie.asset(
'assets/10219-notification-dot.json',
),
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: () {},
child: Text('Show Lottie'),
),
RaisedButton(
onPressed: () {},
child: Text('Hide Lottie'),
),
],
),
],
),
),
),
);
}
}
解决方案
我通过使用setState
和Visibility
小部件解决了这个问题,这是我的代码:
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var _isShow = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Lottie Flutter'),
),
body: Container(
width: double.infinity,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
SizedBox(
width: 50,
height: 50,
child: Visibility(
visible: _isShow,
child: Lottie.asset(
'assets/10219-notification-dot.json',
),
),
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: () {
setState(() {
_isShow = true;
});
},
child: Text('Show Lottie'),
),
RaisedButton(
onPressed: () {
setState(() {
_isShow = false;
});
},
child: Text('Hide Lottie'),
),
],
),
],
),
),
),
);
}
}
推荐阅读
- git - Git pull 覆盖并且不合并或确认同一分支(主)上的冲突
- excel - 添加 nlog 后 Excel 插件不再工作(与 addin-express 一起安装)
- javascript - React : Invariant Violation: 对象作为 React 子对象无效
- python - Pyinstaller EXE: FileNotFoundError: No such file or directory 'C:\\Users\\my.name\\Desktop\\EPE 2.0\\dist\\main\\timezonefinder\\timezone_names.json'
- r - 字符串匹配,其中字符串包含标点符号
- bash - bash:基本的 if 条件不起作用?(字符串比较)
- javascript - 如何触发自定义复选框小部件
- javascript - reactJs 中的组件
- javascript - 显示未捕获的引用错误
- laravel - 原始 SQL 到 Eloquent