call method

T call(
  1. {bool suppressWarning = false}
)
inherited

Returns the object of type T created by the factory.

If an object has not been created yet, this triggers the factory, which was set in the constructor, to create one.

// The factory is not executed immediately when a pot is created.
final counterPot = Pot(() => Counter(0));

// The factory is triggered when the object is first accessed.
final counter = counterPot();

It also applies to the first access after a reset.

final counterPot = Pot(() => Counter(0));

// An object is created.
var counter = counterPot();

// The object is discarded.
counterPot.reset();

// A new object is created again.
counter = counterPot();

The object exists while the scope where it was created exists, so it is discarded when the scope is removed.

final counterPot = Pot(() => Counter(0));

void main() {
  // A new scope is added, and the `currentScope` turns 1.
  // The object is not bound to the scope yet because it hasn't created.
  Pot.pushScope();

  // An object is created and set in the current scope 1.
  final counter = counterPot();

  // The object is discarded.
  // The scope 1 is removed and the `currentScope` turns 0.
  Pot.popScope();
}

Implementation

T call({bool suppressWarning = false}) {
  if (_isDisposed) {
    throwStateError();
  }

  if (!_hasObject) {
    debugWarning(suppressWarning: suppressWarning);

    _scope = StaticPot.currentScope;
    _prevScope = _scope;

    StaticPot.scopes
      ..removePot(_pot, excludeCurrentScope: true)
      ..addPot(_pot);

    _object = _factory();
    _hasObject = true;

    StaticPot.eventHandler.addEvent(PotEventKind.created, pots: [_pot]);
  }
  return _object as T;
}