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();
Please help
CodePudding user response:
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;
DateTime? _endTime;
Timer? _timer;
CountDownTimer({
required this.total,
required this.interval,
required this.onTick,
required this.onFinish,
});
void start() {
_endTime = DateTime.now().add(total);
_timer = Timer.periodic(interval, _onInterval);
}
void cancel() {
_timer?.cancel();
}
void _onInterval(Timer _) {
var timeLeft = _endTime!.difference(DateTime.now());
if (timeLeft <= Duration.zero) {
// The last time the [onTick] callback was invoked, there were still
// an [interval] amount of time left, so the caller expects [onTick]
// to fire a final time.
_timer!.cancel();
onTick(Duration.zero);
onFinish();
return;
} else if (timeLeft < interval) {
// Cancel the periodic [Timer] and replace it with a one-shot [Timer]
// for the remaining time.
_timer!.cancel();
_timer = Timer(timeLeft, onFinish);
}
onTick(timeLeft);
}
}
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
Durationinstead of integers representing milliseconds. - Takes
onTickandonFinishcallbacks instead of expecting you to extend the class with overrides. - The
onTickbehavior 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.
