Search code examples
flutterdarttimercountdown

How can I execute a function during the count-down timer?


I want to collect some real-time values during a time period and then proceed accordingly. Below is the code of java android studio. However, I cannot find any way to execute a function during the count-down timer in dart.

timer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {


            sum = Math.round(Math.sqrt(Math.pow(event.values[0], 2)
                    + Math.pow(event.values[1], 2)
                    + Math.pow(event.values[2], 2)));
            repeat_count++;
            Log.e("Check sum", String.valueOf(sum));
            if ((sum >= 9.80) && (sum <= 11.0)) {
                count++;
            }

        }


        public void onFinish() {
            String c = String.valueOf(count);
            String rep=String.valueOf(repeat_count);
            Log.e("Count is", c);
            Log.e("Loop count",rep);
            Intent intent=new Intent();
            intent.putExtra("count_value",count);
            setResult(2, intent);
            finish();


        }
    }.start();

Solution

  • I cannot find any way to execute a function during the count-down timer in dart.

    It's not very clear what you're asking. Dart doesn't have a CountDownTimer class if that's what you mean, but you could implement one yourself without much trouble. You mostly just need to use Timer.periodic to invoke a callback at regular intervals and then to cancel that Timer after a sufficient total amount of time has elapsed.

    An implementation that is more similar to the Android version:

    import 'dart:async';
    
    class CountDownTimer {
      final Duration total;
      final Duration interval;
    
      final void Function(Duration) onTick;
      final void Function() onFinish;
    
      Timer? _periodicTimer;
      Timer? _completionTimer;
    
      CountDownTimer({
        required this.total,
        required this.interval,
        required this.onTick,
        required this.onFinish,
      });
    
      void start() {
        var endTime = DateTime.now().add(total);
        _periodicTimer = Timer.periodic(interval, (_) {
          var timeLeft = endTime.difference(DateTime.now());
          onTick(timeLeft);
        });
        _completionTimer = Timer(total, () {
          _periodicTimer!.cancel();
          onFinish();
        });
      }
    
      void cancel() {
        _periodicTimer?.cancel();
        _completionTimer?.cancel();
      }
    }
    
    void main() {
      var countDownTimer = CountDownTimer(
        total: const Duration(seconds: 30),
        interval: const Duration(seconds: 1),
        onTick: (timeLeft) {
          print(timeLeft);
        },
        onFinish: () {
          print('Done');
        },
      );
      countDownTimer.start();
    }
    

    Notable differences from the Android version:

    • Uses a Duration instead of integers representing milliseconds.
    • Takes onTick and onFinish callbacks instead of expecting you to extend the class with overrides.
    • The onTick behavior might be slightly different with regard to the initial and final calls. The documentation for the Android version doesn't explain what that behavior is supposed to be, so I picked behavior that I personally think is reasonable.

    Edit: Updated with a simpler implementation by maintaining two separate Timer objects.