of method Null safety
- BuildContext context
Finds the ScaffoldState from the closest instance of this class that encloses the given context.
If no instance of this class encloses the given context, will cause an assert in debug mode, and throw an exception in release mode.
This method can be expensive (it walks the element tree).
build
method of a child of a Scaffold.
flutter create --sample=material.Scaffold.of.1 mysample
build
function, the
context
argument to the build
function can't be used to find the
Scaffold (since it's "above" the widget being returned in the widget
tree). In such cases, the following technique with a Builder can be used
to provide a new scope with a BuildContext that is "under" the
Scaffold:
flutter create --sample=material.Scaffold.of.2 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 Scaffold. In this solution, you would have an outer widget that creates the Scaffold populated by instances of your new inner widgets, and then in these inner widgets you would use Scaffold.of.
A less elegant but more expedient solution is assign a GlobalKey to the
Scaffold, then use the key.currentState
property to obtain the
ScaffoldState rather than using the Scaffold.of function.
If there is no Scaffold in scope, then this will throw an exception. To return null if there is no Scaffold, use maybeOf instead.
Implementation
static ScaffoldState of(BuildContext context) {
assert(context != null);
final ScaffoldState? result = context.findAncestorStateOfType<ScaffoldState>();
if (result != null) {
return result;
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'Scaffold.of() called with a context that does not contain a Scaffold.',
),
ErrorDescription(
'No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). '
'This usually happens when the context provided is from the same StatefulWidget as that '
'whose build function actually creates the Scaffold 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 Scaffold. For an example of this, please see the '
'documentation for Scaffold.of():\n'
' https://api.flutter.dev/flutter/material/Scaffold/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 Scaffold. In this solution, '
'you would have an outer widget that creates the Scaffold populated by instances of '
'your new inner widgets, and then in these inner widgets you would use Scaffold.of().\n'
'A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, '
'then use the key.currentState property to obtain the ScaffoldState rather than '
'using the Scaffold.of() function.',
),
context.describeElement('The context used was'),
]);
}