query static method

Future<NtpResponse> query({
  1. bool isUtc = false,
  2. NtpServer server = NtpServer.google,
  3. String? customServer,
  4. List<NtpServer>? fallbackServers,
  5. int port = 123,
  6. int timeout = 5,
  7. int samples = 1,
  8. bool forceRefresh = false,
})

Queries accurate time and returns a full NtpResponse with telemetry (offset, round-trip delay, stratum, referenceId, etc.).

Uses cached telemetry if the cache is fresh and forceRefresh is false, updating NtpResponse.dateTime to the current instant.

Implementation

static Future<NtpResponse> query({
  bool isUtc = false,
  NtpServer server = NtpServer.google,
  String? customServer,
  List<NtpServer>? fallbackServers,
  int port = 123,
  int timeout = 5,
  int samples = 1,
  bool forceRefresh = false,
}) async {
  final nowLocal = DateTime.now();
  final hasFreshCache = _isCacheFresh(nowLocal) && _lastSyncDetails != null;

  if (forceRefresh || !hasFreshCache) {
    await _syncNtpTime(
      servers: _buildServerList(server, customServer, fallbackServers),
      port: port,
      timeout: timeout,
      samples: samples,
    );
  }

  final details = _lastSyncDetails!;
  final currentCorrected =
      DateTime.now().add(_cachedOffset ?? details.offset);
  return NtpResponse(
    dateTime: isUtc ? currentCorrected.toUtc() : currentCorrected.toLocal(),
    offset: details.offset,
    roundTripDelay: details.roundTripDelay,
    server: details.server,
    stratum: details.stratum,
    leapIndicator: details.leapIndicator,
    referenceId: details.referenceId,
    rootDelay: details.rootDelay,
    rootDispersion: details.rootDispersion,
  );
}