Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce repetitive Theme.of() calls #438

Merged
merged 1 commit into from Dec 2, 2022
Merged

Reduce repetitive Theme.of() calls #438

merged 1 commit into from Dec 2, 2022

Conversation

jpnurmi
Copy link
Member

@jpnurmi jpnurmi commented Dec 2, 2022

It's not an expensive call, but not free either. Every Theme.of() call implies a Localizations.of() call, so two inherited widget lookups both of which are basically hashmap lookups. Last but not least, the two are merged and cached, resulting in a third hashmap lookup. Therefore it's nice to store the theme data to a variable at the beginning of build() to avoid repeating the hashmap lookups several times.

  static ThemeData of(BuildContext context) {
    final _InheritedTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedTheme>(); // <== 1
    final MaterialLocalizations? localizations = Localizations.of<MaterialLocalizations>(context, MaterialLocalizations); // <== 2
    final ScriptCategory category = localizations?.scriptCategory ?? ScriptCategory.englishLike;
    final ThemeData theme = inheritedTheme?.theme.data ?? _kFallbackTheme;
    return ThemeData.localize(theme, theme.typography.geometryThemeFor(category)); // <== 3
  }

https://github.com/flutter/flutter/blob/5c97543027f62bf73062db5e06b1b1b9d5636dd1/packages/flutter/lib/src/material/theme.dart#L107-L113

It's not an expensive call, but not free either. Every `Theme.of()` call
implies a `Localizations.of()` call, both of which are basically hashmap
lookups. Last but not least, the two are merged and cached, resulting in
a third hashmap lookup. Therefore it's nice to store it to a variable in
the beginning of `build()` to avoid doing all three hashmap lookups every
time the theme is accessed.
@Feichtmeier Feichtmeier merged commit 4652517 into ubuntu:main Dec 2, 2022
@jpnurmi jpnurmi deleted the theme-of branch December 2, 2022 18:48
@jpnurmi jpnurmi mentioned this pull request Jan 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants