withFrozenTime<T> static method

Future<T> withFrozenTime<T>(
  1. DateTime time,
  2. Future<T> callback()
)

Execute a callback with a specific frozen time, then restore.

Example:

await NyTime.withFrozenTime(DateTime(2025, 1, 1), () async {
  // Time is frozen to 2025-01-01 here
  await someAsyncOperation();
});
// Time is back to normal here

Implementation

static Future<T> withFrozenTime<T>(
  DateTime time,
  Future<T> Function() callback,
) async {
  final previous = _testNow;
  _testNow = time;
  try {
    return await callback();
  } finally {
    _testNow = previous;
  }
}