71 lines
2.1 KiB
Dart
71 lines
2.1 KiB
Dart
import 'dart:async';
|
|
import 'package:flutter/material.dart';
|
|
|
|
class RemainingTime {
|
|
ValueNotifier<int> remainingSeconds = ValueNotifier<int>(0);
|
|
ValueNotifier<bool> canResend = ValueNotifier<bool>(false);
|
|
DateTime? _expiryTime;
|
|
Timer? _timer;
|
|
|
|
void initializeFromExpiry({required dynamic expiryTime}) {
|
|
try {
|
|
if (expiryTime is DateTime) {
|
|
_expiryTime = expiryTime.toUtc();
|
|
} else if (expiryTime is String) {
|
|
if (expiryTime.contains('-') && expiryTime.contains(':')) {
|
|
_expiryTime = DateTime.parse(expiryTime).toUtc();
|
|
} else {
|
|
_expiryTime =
|
|
DateTime.fromMillisecondsSinceEpoch(int.parse(expiryTime))
|
|
.toUtc();
|
|
}
|
|
} else {
|
|
throw ArgumentError("Invalid type for expiryTime");
|
|
}
|
|
_updateRemainingSeconds();
|
|
startTimer();
|
|
} catch (e) {
|
|
debugPrint("Error initializing timer: $e");
|
|
remainingSeconds.value = 0;
|
|
canResend.value = true;
|
|
}
|
|
}
|
|
|
|
void _updateRemainingSeconds() {
|
|
final now = DateTime.now().toUtc();
|
|
if (_expiryTime == null) return;
|
|
final difference = _expiryTime!.difference(now).inSeconds;
|
|
remainingSeconds.value = difference > 0 ? difference : 0;
|
|
canResend.value = remainingSeconds.value <= 0;
|
|
}
|
|
|
|
void startTimer() {
|
|
_timer?.cancel();
|
|
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
|
_updateRemainingSeconds();
|
|
if (remainingSeconds.value <= 0) {
|
|
timer.cancel();
|
|
}
|
|
});
|
|
}
|
|
|
|
String formatTime() {
|
|
final seconds = remainingSeconds.value;
|
|
if (seconds >= 3600) {
|
|
final hours = (seconds ~/ 3600).toString().padLeft(2, '0');
|
|
final minutes = ((seconds % 3600) ~/ 60).toString().padLeft(2, '0');
|
|
final secs = (seconds % 60).toString().padLeft(2, '0');
|
|
return "$hours:$minutes:$secs";
|
|
} else {
|
|
final minutes = (seconds ~/ 60).toString().padLeft(2, '0');
|
|
final secs = (seconds % 60).toString().padLeft(2, '0');
|
|
return "$minutes:$secs";
|
|
}
|
|
}
|
|
|
|
void dispose() {
|
|
_timer?.cancel();
|
|
remainingSeconds.dispose();
|
|
canResend.dispose();
|
|
}
|
|
} |