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

Flutter中实现Countup组件随机自动停止与手动停止功能

实现Countup的两种停止方式

你需要用StatefulWidget来管理计数的状态,以此实现手动停止和随机自动停止的需求,以下是具体实现方案:

核心思路

  1. 用状态变量控制计数启停、记录当前数值和随机停止目标值
  2. 手动停止:通过按钮触发状态变更,让计数停在当前数值
  3. 随机自动停止:初始化时生成随机目标值,监听计数进度,达到目标值时自动停止

完整代码示例

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:countup/countup.dart';

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

  @override
  State<CountupWithStop> createState() => _CountupWithStopState();
}

class _CountupWithStopState extends State<CountupWithStop> {
  bool _isCounting = true;
  late int _randomStopTarget;
  double _currentCount = 0;

  @override
  void initState() {
    super.initState();
    // 生成0-100之间的随机停止目标值
    _randomStopTarget = Random().nextInt(101);
    // 启动监听逻辑,达到随机值就停止
    Future.doWhile(() async {
      await Future.delayed(const Duration(milliseconds: 30));
      if (_currentCount >= _randomStopTarget && _isCounting) {
        setState(() => _isCounting = false);
        return false;
      }
      return _isCounting;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Countup(
              begin: 0,
              // 计数中就往100走,停止了就停在当前数值
              end: _isCounting ? 100 : _currentCount,
              duration: const Duration(seconds: 5),
              separator: ',',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 22,
              ),
              // 实时更新当前计数数值
              onUpdate: (value) => _currentCount = value,
              // 自然走到100时标记停止
              onEnd: () => setState(() => _isCounting = false),
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: _isCounting
                  ? () => setState(() => _isCounting = false)
                  : null,
              child: const Text('停止计数'),
            ),
          ],
        ),
      ),
    );
  }
}

关键逻辑说明

  • 随机自动停止:初始化时生成0到100的随机数,通过循环监听当前计数进度,一旦达到随机目标值就立即停止计数
  • 手动停止:按钮点击后切换_isCounting状态,同时把Countup的end值改为当前记录的_currentCount,让计数停在当前位置
  • onUpdate回调用来实时同步当前计数数值,确保停止时能精准保留当前值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:07:07