of static method

ThemeData of(
  1. BuildContext context
)

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 ThemeData.fallback if there is no Theme in the given build context.

Typical usage is as follows:

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

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(),
    home: 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.titleLarge,
          ),
        );
      },
    ),
  );
}

Implementation

static ThemeData of(BuildContext context) {
  final _InheritedTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedTheme>();
  final MaterialLocalizations? localizations = Localizations.of<MaterialLocalizations>(context, MaterialLocalizations);
  final ScriptCategory category = localizations?.scriptCategory ?? ScriptCategory.englishLike;
  final InheritedCupertinoTheme? inheritedCupertinoTheme = context.dependOnInheritedWidgetOfExactType<InheritedCupertinoTheme>();
  final ThemeData theme = inheritedTheme?.theme.data ?? (
    inheritedCupertinoTheme != null ? CupertinoBasedMaterialThemeData(themeData: inheritedCupertinoTheme.theme.data).materialTheme : _kFallbackTheme
  );
  return ThemeData.localize(theme, theme.typography.geometryThemeFor(category));
}