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

Flutter 2分钟倒计时到期自动重启及发起服务端请求问题求解

2分钟自动循环倒计时实现问题

需求为开发时长2分钟的倒计时器,满足:

  • 计时结束后自动重新开始
  • 计时结束时向服务端发起请求
    现有代码已完成基础倒计时渲染,但未实现到期重启、服务端请求逻辑。

现有代码

Countdown 倒计时组件

class Countdown extends AnimatedWidget {
  Countdown({Key? key, required this.animation})
      : super(key: key, listenable: animation);
  Animation<int> animation;

  @override
  build(BuildContext context) {
    Duration clockTimer = Duration(seconds: animation.value);

    String timerText =
        '${clockTimer.inMinutes.remainder(60).toString()}:${clockTimer.inSeconds.remainder(60).toString().padLeft(2, '0')}';

    return Text(
      "$timerText ",
      style: TextStyle(
        fontSize: 14.sp,
        color: AppColors.DARK_GREY,
      ),
    );
  }
}

倒计时组件调用代码

Countdown(
  animation: StepTween(
    begin: controller.levelClock.value, // 倒计时总时长
    end: 0,
  ).animate(controller.animationController!),
),

原有页面控制器代码

RxInt levelClock = 120.obs;
AnimationController? animationController;

@override
void onInit() {
  animationController = AnimationController(
      vsync: this, duration: Duration(seconds: levelClock.value));

  animationController!.forward();
  super.onInit();
}

实现方案

核心逻辑是给AnimationController添加动画状态监听,在动画执行完成(即倒计时归0)时,先触发服务端请求,再重置动画重新启动即可,倒计时组件本身不需要修改。

修改后的控制器代码

RxInt levelClock = 120.obs;
AnimationController? animationController;

@override
void onInit() {
  animationController = AnimationController(
      vsync: this, duration: Duration(seconds: levelClock.value));

  // 监听动画运行状态
  animationController!.addStatusListener((status) async {
    // 动画执行完成 = 倒计时结束
    if (status == AnimationStatus.completed) {
      // 替换为你的服务端请求逻辑
      // 示例:await ApiService().reportTimerEnd();

      // 重置动画状态并重新启动倒计时
      animationController!.reset();
      animationController!.forward();
    }
  });

  animationController!.forward();
  super.onInit();
}

@override
void onClose() {
  // 页面销毁时释放动画控制器,避免内存泄漏
  animationController?.dispose();
  super.onClose();
}

补充说明

  • 如果后续需要调整倒计时时长,修改levelClock值后,重新给animationController的duration属性赋值,再调用reset()和forward()即可生效
  • 服务端请求的加载状态、错误提示等逻辑,可以直接写在状态监听的判断分支内
  • 不需要修改现有Countdown组件的渲染逻辑,动画变化会自动同步到UI

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:32:30