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

Flutter中如何在LineProgressIndicator上添加随进度值移动的图标

在Flutter中实现带跟随图标的线性进度指示器

要实现图标随LinearProgressIndicator进度同步移动的效果,核心是用Stack叠加进度条与图标,通过进度值动态计算图标位置,具体实现如下:

实现思路

  • 用Stack布局让图标覆盖在进度条上方
  • 根据当前进度值计算图标水平偏移:进度条宽度 × 进度值,再减去图标一半宽度,确保图标中心对齐进度末端
  • 用StatefulWidget维护进度状态,实时触发UI更新同步图标位置

完整代码示例

import 'dart:async';
import 'package:flutter/material.dart';

class ProgressWithIcon extends StatefulWidget {
  const ProgressWithIcon({super.key});

  @override
  State<ProgressWithIcon> createState() => _ProgressWithIconState();
}

class _ProgressWithIconState extends State<ProgressWithIcon> {
  double _progress = 0.0;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    // 模拟进度增长逻辑
    _timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      setState(() {
        _progress += 0.01;
        if (_progress >= 1.0) {
          _timer.cancel();
          _progress = 1.0;
        }
      });
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 进度条总宽度(适配屏幕)
    final progressBarWidth = MediaQuery.of(context).size.width - 40;
    // 图标尺寸
    const iconSize = 24.0;
    // 计算图标偏移量
    final iconOffset = _progress * progressBarWidth - iconSize / 2;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Stack(
        alignment: Alignment.centerLeft,
        children: [
          // 基础线性进度条
          LinearProgressIndicator(
            value: _progress,
            minHeight: 8,
            borderRadius: BorderRadius.circular(4),
            backgroundColor: Colors.grey[300],
            valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
          ),
          // 跟随进度移动的图标
          Transform.translate(
            offset: Offset(iconOffset, 0),
            child: const Icon(
              Icons.circle,
              size: iconSize,
              color: Colors.blue,
            ),
          ),
        ],
      ),
    );
  }
}

// 使用示例
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Center(child: ProgressWithIcon()),
    ),
  ));
}

关键细节说明

  • Transform.translate相比Positioned更适合这种百分比偏移的场景,计算更灵活
  • 偏移量减去图标一半宽度,是为了让图标中心精准对齐进度条末端,视觉效果更协调
  • 示例中用Timer模拟进度增长,实际业务中可替换为真实的进度数据源(如文件下载进度、任务完成度等)

内容的提问来源于stack exchange,提问作者Timothy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:15:40