now method
Fetches the current server time from the configured HTTP API.
Sends an HTTP GET request to the API endpoint defined by _api.
If the response status code is not 200, throws an Exception
describing the HTTP error.
The method expects the body to contain a date string in the format:
"EEE, dd MMM yyyy HH:mm:ss 'GMT'". This string is parsed into a UTC
DateTime and returned.
Throws an Exception if the HTTP request fails, times out, or the date parsing does not succeed.
Implementation
@override
Future<DateTime> now() async {
final uri = Uri.parse(apiUrl ?? _api);
final startTime = DateTime.now();
final response = await http.get(uri).timeout(
Duration(seconds: timeout),
onTimeout: () {
throw Exception('Timeout fetching time from API');
},
);
final endTime = DateTime.now();
if (response.statusCode != 200) {
throw Exception(
'Error ${response.statusCode}: failed to fetch time from API',
);
}
try {
DateTime serverDate;
if (parseResponse != null) {
serverDate = parseResponse!(response);
} else {
final String stringDate = response.body;
final DateFormat format =
DateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", 'en_US');
serverDate = format.parse(stringDate, true);
}
final latency = endTime.difference(startTime);
final correctedTime = serverDate.add(latency ~/ 2);
return isUtc ? correctedTime.toUtc() : correctedTime;
} catch (e) {
throw Exception('Error parsing time from API: $e');
}
}