TechnicalMedium Flutter

What is BuildContext in Flutter?

Asked for Mobile Developer

Why they ask this: Misusing BuildContext causes common runtime errors, so this tests deeper Flutter knowledge.

Answer

A BuildContext is a handle to a widget's location in the widget tree (it is actually the widget's Element). It is used to look up the tree for inherited data and services:

text
final theme = Theme.of(context);
final size = MediaQuery.sizeOf(context);
Navigator.of(context).push(MaterialPageRoute(builder: (_) => const JobScreen()));
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Saved')));

Common pitfalls:

  • Scaffold.of(context) fails if context belongs to a widget above the Scaffold. Wrap the child in a Builder to get a context below it.
  • After an await, the widget may have been removed. Check if (!context.mounted) return; before using the context again.

Can you explain this in your own words?

Back to question bank