maybeOf static method

ScrollableState? maybeOf(
  1. BuildContext context,
  2. {Axis? axis}
)

The state from the closest instance of this class that encloses the given context, or null if none is found.

Typical usage is as follows:

ScrollableState? scrollable = Scrollable.maybeOf(context);

Calling this method will create a dependency on the ScrollableState that is returned, if there is one. This is typically the closest Scrollable, but may be a more distant ancestor if axis is used to target a specific Scrollable.

Using the optional Axis is useful when Scrollables are nested and the target Scrollable is not the closest instance. When axis is provided, the nearest enclosing ScrollableState in that Axis is returned, or null if there is none.

This finds the nearest ancestor Scrollable of the context. This means that if the context is that of a Scrollable, it will not find that Scrollable.

See also:

Implementation

static ScrollableState? maybeOf(BuildContext context, { Axis? axis }) {
  // This is the context that will need to establish the dependency.
  final BuildContext originalContext = context;
  InheritedElement? element = context.getElementForInheritedWidgetOfExactType<_ScrollableScope>();
  while (element != null) {
    final ScrollableState scrollable = (element.widget as _ScrollableScope).scrollable;
    if (axis == null || axisDirectionToAxis(scrollable.axisDirection) == axis) {
      // Establish the dependency on the correct context.
      originalContext.dependOnInheritedElement(element);
      return scrollable;
    }
    context = scrollable.context;
    element = context.getElementForInheritedWidgetOfExactType<_ScrollableScope>();
  }
  return null;
}