now static method

Future<DateTime> now({
  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,
  9. bool allowFallback = true,
})

Returns the current accurate time.

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

If server is specified (defaults to NtpServer.google), it queries that server. You can also provide a custom raw server URL string via customServer, or a list of fallbackServers to try automatically if the primary server fails.

When samples > 1, performs multi-sample clock filtering and selects the measurement with the lowest round-trip delay.

If forceRefresh is true, a network request is forced even if a fresh cache exists.

If allowFallback is true (default), returns the local device time on failure instead of throwing an error.

Implementation

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

  if (forceRefresh || (!hasFreshCache && !inCooldown) || hasOngoingSync) {
    try {
      await _syncNtpTime(
        servers: _buildServerList(server, customServer, fallbackServers),
        port: port,
        timeout: timeout,
        samples: samples,
      );
    } catch (e) {
      if (!allowFallback) {
        rethrow;
      }
    }
  }

  final corrected = DateTime.now().add(_cachedOffset ?? Duration.zero);
  return isUtc ? corrected.toUtc() : corrected.toLocal();
}