get<R extends Bloc> static method

R get<R extends Bloc>({
  1. BuildContext? context,
  2. dynamic arg,
  3. bool useCache = true,
})

Called whenever an application needs an already added Bloc

The blocs which are once instantiated, can also be cached using the useCache option The bloc type T and the provided arg are both matched to return the cached bloc

Implementation

static R get<R extends Bloc>({
  BuildContext? context,
  arg,
  bool useCache = true,
}) {
  if (!_blocs.containsKey(R)) {
    throw ArgumentError(
      '$R was not found in this container. Did you forgot to add() it',
    );
  }

  if (!useCache) {
    return _blocs[R]!(context, arg);
  }

  final cacheKey = TypeAndArg(R, arg);

  R cachedBloc;

  try {
    final entry = _cache.entries.firstWhere((e) => e.key == cacheKey);
    cachedBloc = entry.value as R;
  } catch (e) {
    cachedBloc = _blocs[R]!(context, arg);
    _cache[cacheKey] = cachedBloc;
  }

  final numCached = _cache.keys.where((e) => e.type == R).length;

  if (numCached > 2) {
    _log.warning('you have already cached $numCached ${R}s');
  }

  return cachedBloc;
}