of method

ThemeData of (BuildContext context, { bool shadowThemeOnly: false })

The data from the closest Theme instance that encloses the given context.

If the given context is enclosed in a Localizations widget providing MaterialLocalizations, the returned data is localized according to the nearest available MaterialLocalizations.

Defaults to new ThemeData.fallback if there is no Theme in the given build context.

If shadowThemeOnly is true and the closest Theme ancestor was installed by the MaterialApp — in other words if the closest Theme ancestor does not shadow the application's theme — then this returns null. This argument should be used in situations where its useful to wrap a route's widgets with a Theme, but only when the application's overall theme is being shadowed by a Theme widget that is deeper in the tree. See isMaterialAppTheme.

Typical usage is as follows:

@override
Widget build(BuildContext context) {
  return Text(
    'Example',
    style: Theme.of(context).textTheme.title,
  );
}

When the Theme is actually created in the same build function (possibly indirectly, e.g. as part of a MaterialApp), the context argument to the build function can't be used to find the Theme (since it's "above" the widget being returned). In such cases, the following technique with a Builder can be used to provide a new scope with a BuildContext that is "under" the Theme:

@override
Widget build(BuildContext context) {
  return MaterialApp(
    theme: ThemeData.light(),
    body: Builder(
      // Create an inner BuildContext so that we can refer to
      // the Theme with Theme.of().
      builder: (BuildContext context) {
        return Center(
          child: Text(
            'Example',
            style: Theme.of(context).textTheme.title,
          ),
        );
      },
    ),
  );
}

Implementation

static ThemeData of(BuildContext context, { bool shadowThemeOnly = false }) {
  final _InheritedTheme inheritedTheme = context.inheritFromWidgetOfExactType(_InheritedTheme);
  if (shadowThemeOnly) {
    if (inheritedTheme == null || inheritedTheme.theme.isMaterialAppTheme)
      return null;
    return inheritedTheme.theme.data;
  }

  final MaterialLocalizations localizations = MaterialLocalizations.of(context);
  final ScriptCategory category = localizations?.scriptCategory ?? ScriptCategory.englishLike;
  final ThemeData theme = inheritedTheme?.theme?.data ?? _kFallbackTheme;
  return ThemeData.localize(theme, theme.typography.geometryThemeFor(category));
}