of static method

TreeSliverController of(
  1. BuildContext context
)

Finds the TreeSliverController for the closest TreeSliver instance that encloses the given context.

If no TreeSliver encloses the given context, calling this method will cause an assert in debug mode, and throw an exception in release mode.

To return null if there is no TreeSliver use maybeOf instead.

Typical usage of the TreeSliverController.of function is to call it from within the build method of a descendant of a TreeSliver.

When the TreeSliver is actually created in the same build function as the callback that refers to the controller, then the context argument to the build function can't be used to find the TreeSliverController (since it's "above" the widget being returned in the widget tree). In cases like that you can add a Builder widget, which provides a new scope with a BuildContext that is "under" the TreeSliver.

Implementation

static TreeSliverController of(BuildContext context) {
  final _TreeSliverState<Object?>? result =
      context.findAncestorStateOfType<_TreeSliverState<Object?>>();
  if (result != null) {
    return result.controller;
  }
  throw FlutterError.fromParts(<DiagnosticsNode>[
    ErrorSummary(
      'TreeController.of() called with a context that does not contain a '
      'TreeSliver.',
    ),
    ErrorDescription(
      'No TreeSliver ancestor could be found starting from the context that '
      'was passed to TreeController.of(). '
      'This usually happens when the context provided is from the same '
      'StatefulWidget as that whose build function actually creates the '
      'TreeSliver widget being sought.',
    ),
    ErrorHint(
      'There are several ways to avoid this problem. The simplest is to use '
      'a Builder to get a context that is "under" the TreeSliver.',
    ),
    ErrorHint(
      'A more efficient solution is to split your build function into '
      'several widgets. This introduces a new context from which you can '
      'obtain the TreeSliver. In this solution, you would have an outer '
      'widget that creates the TreeSliver populated by instances of your new '
      'inner widgets, and then in these inner widgets you would use '
      'TreeController.of().',
    ),
    context.describeElement('The context used was'),
  ]);
}