PerformanceMedium30 XP3 min read
Why should you avoid calling BuildContext.of() methods in build() repeatedly?
TL;DR: Each Theme.of(context), MediaQuery.of(context), etc. call walks up the element tree to find the nearest InheritedWidget. Calling them multiple times in one build() is redundant — cache the value in a local variable.
Full Answer
InheritedWidget lookups (Theme.of, Navigator.of, MediaQuery.of) traverse the element tree upward. This is fast individually but becomes measurable if called dozens of times per frame.
Best Practices
- ▸Cache at the top of build(): final theme = Theme.of(context)
- ▸Use context.watch<T>() in Provider for scoped rebuilds
- ▸Prefer Theme.of(context).textTheme.bodyMedium over calling Theme.of() 5 times for different text styles
- ▸MediaQuery.sizeOf(context) (Flutter 3.10+) rebuilds only on size changes, not all MediaQuery changes
🎯
Flutter 3.10 added MediaQuery.sizeOf, MediaQuery.paddingOf, etc. — these register more granular dependencies so your widget only rebuilds when that specific value changes.
Code Examples
dartCaching context lookups
Output
// Same result, 75% fewer tree traversals
Common Mistakes
- ✗Calling MediaQuery.of(context) deeply inside nested builds — creates subscriptions for every callee
- ✗Not using the granular MediaQuery.sizeOf() in Flutter 3.10+
Interview Tip
💡
This shows you understand that .of() isn't just a getter — it creates a dependency subscription. Caching prevents multiple subscriptions to the same InheritedWidget.
#build-context#inherited-widget#of-method#performance