Flutter实现GIF播放1-2秒后切换显示PNG图片的方法
实现GIF播放1-2秒后切换显示PNG的方案
你可以通过状态管理+定时器来实现这个需求,以下是具体代码实现:
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; class AnimatedCheckbox extends StatefulWidget { final Color uncheckedColor; const AnimatedCheckbox({super.key, required this.uncheckedColor}); @override State<AnimatedCheckbox> createState() => _AnimatedCheckboxState(); } class _AnimatedCheckboxState extends State<AnimatedCheckbox> { bool _showGif = true; Timer? _hideGifTimer; @override void initState() { super.initState(); // 生成1-2秒之间的随机延迟时间 final delay = Random().nextInt(1000) + 1000; // 范围1000ms到2000ms _hideGifTimer = Timer(Duration(milliseconds: delay), () { if (mounted) { setState(() { _showGif = false; }); } }); } @override void dispose() { // 页面销毁时取消定时器,避免内存泄漏 _hideGifTimer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Stack( children: [ // 始终显示PNG图片 Image.asset( "assets/Icon/Checkbox.png", color: widget.uncheckedColor, height: 22, width: 22, ), // 仅在_showGif为true时显示GIF if (_showGif) Image.asset( "assets/Icon/fullyComplete1.gif", color: widget.uncheckedColor, scale: 2.5, opacity: const AlwaysStoppedAnimation<double>(1.0), height: 22, width: 22, gaplessPlayback: true, ), ], ); } }
关键说明:
- 用
StatefulWidget管理动态UI状态,通过_showGif布尔值控制GIF的显示/隐藏 - 在
initState中创建定时器,随机生成1-2秒的延迟(如果需要固定时长,直接写Duration(seconds: 1)或Duration(milliseconds: 2000)即可) - 定时器触发后调用
setState更新状态,隐藏GIF - 在
dispose中取消定时器,防止页面销毁后定时器仍运行导致内存泄漏 - 通过
if (_showGif)条件渲染,仅在状态为true时加载显示GIF
内容的提问来源于stack exchange,提问作者Yashraj
相关产品推荐
相关产品推荐

