You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 02:03:21