Flutter如何实现多个倒计时进度条

在Flutter中,如何在一个页面同时显示多个倒计时进度条?每个进度条需要独立控制倒计时时间,并且能够实时更新UI。目前使用Timer或StreamBuilder实现单个倒计时没问题,但多个同时运行时会出现卡顿或互相干扰的情况。请问有没有高效的实现方案,比如如何管理多个计时器的状态,或者推荐适合的插件?最好能附带核心代码示例。

2 回复

使用Timer.periodic配合setState实现多个倒计时进度条。为每个进度条创建独立的计时器和状态变量,通过ListView.builder构建列表,在dispose中取消计时器避免内存泄漏。

更多关于Flutter如何实现多个倒计时进度条的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现多个倒计时进度条,可以通过以下步骤实现:

1. 使用计时器与状态管理

每个进度条需要独立的计时器和状态管理。推荐使用Timer.periodic结合setState或状态管理库(如Provider、Riverpod)。

2. 核心代码示例

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

class CountdownProgressBar extends StatefulWidget {
  final int totalSeconds;
  final String label;

  const CountdownProgressBar({
    Key? key,
    required this.totalSeconds,
    required this.label,
  }) : super(key: key);

  @override
  _CountdownProgressBarState createState() => _CountdownProgressBarState();
}

class _CountdownProgressBarState extends State<CountdownProgressBar> {
  late int _remainingSeconds;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _remainingSeconds = widget.totalSeconds;
    _startTimer();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_remainingSeconds > 0) {
          _remainingSeconds--;
        } else {
          _timer.cancel();
        }
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    double progress = _remainingSeconds / widget.totalSeconds;
    
    return Column(
      children: [
        Text(widget.label),
        LinearProgressIndicator(
          value: progress,
          backgroundColor: Colors.grey,
          valueColor: AlwaysStoppedAnimation<Color>(
            progress > 0.5 ? Colors.green : Colors.red,
          ),
        ),
        Text('${_remainingSeconds}s'),
      ],
    );
  }
}

// 使用示例
class MultipleCountdownScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          CountdownProgressBar(totalSeconds: 60, label: '任务1'),
          CountdownProgressBar(totalSeconds: 120, label: '任务2'),
          CountdownProgressBar(totalSeconds: 90, label: '任务3'),
        ],
      ),
    );
  }
}

3. 关键要点

  • 独立状态:每个进度条维护自己的计时器和剩余时间
  • 进度计算progress = 剩余时间 / 总时间
  • 自动取消:在dispose中取消计时器防止内存泄漏
  • UI更新:通过setState触发界面重绘

4. 优化建议

  • 使用AnimatedContainer实现平滑动画
  • 添加暂停/继续功能
  • 使用CircularProgressIndicator实现圆形进度条
  • 通过状态管理库管理多个计时器状态

这样即可实现多个独立运行的倒计时进度条,每个都有完整的计时功能和视觉反馈。

回到顶部