of static method

ScaffoldMessengerState of(
  1. BuildContext context
)

The state from the closest instance of this class that encloses the given context.

Typical usage of the ScaffoldMessenger.of function is to call it in response to a user gesture or an application state change.
link

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.

Sometimes SnackBars are produced by code that doesn't have ready access to a valid BuildContext. One such example of this is when you show a SnackBar from a method outside of the 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.
link

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:

Implementation

static ScaffoldMessengerState of(BuildContext context) {
  assert(debugCheckHasScaffoldMessenger(context));

  final _ScaffoldMessengerScope scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>()!;
  return scope._scaffoldMessengerState;
}