Once<T extends Object?> class final

Lazy initialization wrapper that computes a value only once and caches it.

Once ensures expensive computations or resource allocations are performed once and reused. Perfect for implementing lazy singletons, caching results, or deferring initialization until first use.

The instance itself is callable via the call method, making usage clean and intuitive.

Example:

// Expensive computation deferred until first access
final expensiveValue = Once(() {
  print('Computing...');
  return complexCalculation();
});

final result1 = expensiveValue(); // Prints 'Computing...', computes value
final result2 = expensiveValue(); // Returns cached value (no computation)

Common use cases:

  • Lazy singleton initialization
  • Expensive resource loading (files, network requests)
  • Heavy computations deferred to first use
  • Caching configuration or expensive lookups
Annotations
  • @experimental

Constructors

Once(T _init())
Creates a lazy initializer with the given _init function.

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

call() → T
Gets or computes the lazy-initialized value.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited