nowSync static method

DateTime nowSync({
  1. bool isUtc = false,
  2. NtpServer server = NtpServer.google,
  3. String? customServer,
  4. List<NtpServer>? fallbackServers,
  5. int port = 123,
  6. int timeout = 5,
})

Returns the current accurate time synchronously using the cached offset.

If isUtc is true, returns the time in UTC. If isUtc is false (default), returns the time in the local time zone.

If the cache has not been initialized yet, it triggers an asynchronous synchronization in the background and returns the local system time.

If the cached value is older than the configured sync interval, a background resynchronization is triggered while still returning the computed time based on the cached offset.

Implementation

static DateTime nowSync({
  bool isUtc = false,
  NtpServer server = NtpServer.google,
  String? customServer,
  List<NtpServer>? fallbackServers,
  int port = 123,
  int timeout = 5,
}) {
  final nowLocal = DateTime.now();
  final shouldSync = !_isCacheFresh(nowLocal);

  if (shouldSync && !_isInCooldown() && _ongoingSync == null) {
    _triggerBackgroundSync(
      servers: _buildServerList(server, customServer, fallbackServers),
      port: port,
      timeout: timeout,
    );
  }

  final offset = _cachedOffset;
  if (offset == null) {
    return isUtc ? nowLocal.toUtc() : nowLocal;
  }

  final corrected = nowLocal.add(offset);
  return isUtc ? corrected.toUtc() : corrected.toLocal();
}