of static method
- BuildContext context
Finds the ExpansionTileController for the closest ExpansionTile instance that encloses the given context.
If no ExpansionTile 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 ExpansionTile use maybeOf instead.
build
method of a descendant of an ExpansionTile.
When the ExpansionTile 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 ExpansionTileController (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 ExpansionTile:
To create a local project with this code sample, run:
flutter create --sample=material.ExpansionTileController.of.1 mysample
A more efficient solution is to split your build function into several widgets. This introduces a new context from which you can obtain the ExpansionTileController. With this approach you would have an outer widget that creates the ExpansionTile populated by instances of your new inner widgets, and then in these inner widgets you would use ExpansionTileController.of.
Implementation
static ExpansionTileController of(BuildContext context) {
final _ExpansionTileState? result = context.findAncestorStateOfType<_ExpansionTileState>();
if (result != null) {
return result._tileController;
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'ExpansionTileController.of() called with a context that does not contain a ExpansionTile.',
),
ErrorDescription(
'No ExpansionTile ancestor could be found starting from the context that was passed to ExpansionTileController.of(). '
'This usually happens when the context provided is from the same StatefulWidget as that '
'whose build function actually creates the ExpansionTile 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 ExpansionTile. For an example of this, please see the '
'documentation for ExpansionTileController.of():\n'
' https://api.flutter.dev/flutter/material/ExpansionTile/of.html',
),
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 ExpansionTile. In this solution, '
'you would have an outer widget that creates the ExpansionTile populated by instances of '
'your new inner widgets, and then in these inner widgets you would use ExpansionTileController.of().\n'
'An other solution is assign a GlobalKey to the ExpansionTile, '
'then use the key.currentState property to obtain the ExpansionTile rather than '
'using the ExpansionTileController.of() function.',
),
context.describeElement('The context used was'),
]);
}