From 2eb7542293b5af23285fc79dd63a6667f2dad605 Mon Sep 17 00:00:00 2001 From: Neeraj Gupta <254676+ua741@users.noreply.github.com> Date: Tue, 14 Mar 2023 04:52:58 +0530 Subject: [PATCH] Improve time counter animation --- lib/ui/code_timer_progress.dart | 37 ++++++++++++++++----------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/lib/ui/code_timer_progress.dart b/lib/ui/code_timer_progress.dart index e34c56a3f4..430bdfad35 100644 --- a/lib/ui/code_timer_progress.dart +++ b/lib/ui/code_timer_progress.dart @@ -1,6 +1,5 @@ -import 'dart:async'; - import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; import 'package:flutter_animation_progress_bar/flutter_animation_progress_bar.dart'; class CodeTimerProgress extends StatefulWidget { @@ -15,43 +14,43 @@ class CodeTimerProgress extends StatefulWidget { _CodeTimerProgressState createState() => _CodeTimerProgressState(); } -class _CodeTimerProgressState extends State { - Timer? _everySecondTimer; - late int _timeRemaining; +class _CodeTimerProgressState extends State + with SingleTickerProviderStateMixin { + late final Ticker _ticker; + double _progress = 0.0; + late final int _microSecondsInPeriod; @override void initState() { super.initState(); - _timeRemaining = widget.period; - _updateTimeRemaining(); - _everySecondTimer = - Timer.periodic(const Duration(milliseconds: 200), (Timer t) { + _microSecondsInPeriod = widget.period * 1000000; + _ticker = createTicker((elapsed) { _updateTimeRemaining(); }); + _ticker.start(); + _updateTimeRemaining(); } void _updateTimeRemaining() { - int newTimeRemaining = - widget.period - (DateTime.now().second % widget.period); - if (newTimeRemaining != _timeRemaining) { - setState(() { - _timeRemaining = newTimeRemaining; - }); - } + int timeRemaining = (_microSecondsInPeriod) - + (DateTime.now().microsecondsSinceEpoch % _microSecondsInPeriod); + setState(() { + _progress = (timeRemaining / _microSecondsInPeriod); + }); } @override void dispose() { - _everySecondTimer?.cancel(); + _ticker.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return FAProgressBar( - currentValue: _timeRemaining / widget.period * 100, + currentValue: _progress * 100, size: 4, - animatedDuration: const Duration(milliseconds: 200), + animatedDuration: const Duration(milliseconds: 10), progressColor: Colors.orange, changeColorValue: 40, changeProgressColor: Colors.green,