of<T> static method

Inheritable<T>? of<T>(
  1. BuildContext context, {
  2. required InheritableAspect<T> aspect,
  3. bool rebuild = true,
  4. bool nullOk = true,
  5. bool mutable = false,
})

Get the nearest enclosing Inheritable for T to context.

Specify nullOk if null should be returned when the enclosing context does not have Inheritable of T.

Implementation

// TODO: if Inheritable is allowed to extend, provide Inheritable.inheriFrom
static Inheritable<T>? of<T>(
  BuildContext context, {
  required InheritableAspect<T> aspect,
  bool rebuild = true,
  bool nullOk = true,
  bool mutable = false,
}) {
  final result =
      _findInheritableSupportingAspect<T>(context, aspect, mutable: mutable);

  if (result == null) {
    if (!nullOk) {
      throw StateError(
        'Unsatisfied dependency Inheritable<$T> for ${context.widget} for aspect: $aspect',
      );
    } else {
      return null;
    }
  }

  assert(!rebuild || aspect is DependableAspect<T>,
      'Only DependableAspect can cause rebuilds');
  if (rebuild && aspect is DependableAspect<T>) {
    context.dependOnInheritedElement(
      result,
      aspect: aspect.ensureHasKey(
        fallback: context.widget.key ?? Key('InheritableAspect<$T>($aspect)'),
      ),
    );
  }

  return result.widget;
}