Meaning of the term .of() in flutter

Viewed 1696

So I was wondering about the Command I use when I close an AlertDialog:

FlatButton(
  child: Text('Okay'),
  onPressed: () {
    Navigator.of(context).pop();
  },
),

What does .of() exactly do? I could not find anything in the flutter dev documentation (Probably because I was missing the correct search term)

Can anyone explain what happens there?

2 Answers

From the documentation of the Navigator class,

Although you can create a navigator directly, it's most common to use the navigator created by the Router which itself is created and configured by a WidgetsApp or a MaterialApp widget. You can refer to that navigator with Navigator.of.

As a general rule, any time you see something along the lines of Classname.of(someObject) in an OO language, .of is a builder that returns an instance of Classname from someObject.

In the Flutter SDK the .of methods are a kind of service locator function that take the framework BuildContext as an argument and return an internal API related to the named class but created by widgets higher up the widget tree. These APIs can then be used by child widgets to access state set on a parent widget and in some cases (such as Navigator) to manipulate them. The pattern encourages componentization and decouples the production of information related to the build tree with its consumption.

In addition to Navigator.of (returns a NavigatorState) there are:

  • Theme.of (returns a ThemeData containing the ambient theme settings)
  • MediaQuery.of (returns a MediaQueryData containing information computed about the device screen size)
  • Directionality.of (returns a TextDirection containing information about text display)

Of course Flutter has non-specific methods for looking up parent widgets from the build context:

context.findAncestorWidgetOfExactType<T extends Widget>()
context.findAncestorStateOfType<T extends State>()
context.findRootAncestorStateOfType<T extends State>()

so Theme.of(context) is really just a static shorthand for context.findAncestorWidgetOfExactType<Theme>().data and Navigator.of(context).pop() is really just a shorthand for context.findAncestorStateOfType<NavigatorState>().pop()

Related