of static method
- BuildContext context
The state from the closest instance of this class that encloses the given context.
To create a local project with this code sample, run:
flutter create --sample=material.ScaffoldMessenger.of.1 mysample
A less elegant but more expedient solution is to assign a GlobalKey to the
ScaffoldMessenger, then use the key.currentState
property to obtain the
ScaffoldMessengerState rather than using the ScaffoldMessenger.of
function. The MaterialApp.scaffoldMessengerKey refers to the root
ScaffoldMessenger that is provided by default.
build
function. In these
cases, you can assign a GlobalKey to the ScaffoldMessenger. This
example shows a key being used to obtain the ScaffoldMessengerState
provided by the MaterialApp.
To create a local project with this code sample, run:
flutter create --sample=material.ScaffoldMessenger.of.2 mysample
If there is no ScaffoldMessenger in scope, then this will assert in debug mode, and throw an exception in release mode.
See also:
- maybeOf, which is a similar function but will return null instead of throwing if there is no ScaffoldMessenger ancestor.
- debugCheckHasScaffoldMessenger, which asserts that the given context has a ScaffoldMessenger ancestor.
Implementation
static ScaffoldMessengerState of(BuildContext context) {
assert(debugCheckHasScaffoldMessenger(context));
final _ScaffoldMessengerScope scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>()!;
return scope._scaffoldMessengerState;
}