BuildContext
- Flutter course
- Beginner
- Lesson 13/99
- 4 min
Learn that BuildContext marks a widget's place in the tree.
BuildContext
BuildContext represents a widget's position in the widget tree. It is passed to the build method and identifies where the widget is and who its parents are. You use context to reach ancestral (ancestor) data such as Theme and MediaQuery.
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Text('Hello', style: theme.textTheme.bodyLarge);
}Accessing ancestors
A widget uses BuildContext to obtain data from its ancestor widgets. Theme.of(context) walks up the tree to find the nearest MaterialApp and returns its theme. Similarly MediaQuery.of(context) gives the screen size.
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return SizedBox(width: width, child: Text('Full'));
}Practice Print context uses
In main, print three lines with print: context konum, Theme tema and MediaQuery boyut.
Starter code
void main() {
// üç satır yazdır:
// context konum
// Theme tema
// MediaQuery boyut
}Sample solution
void main() {
print('context konum');
print('Theme tema');
print('MediaQuery boyut');
}Expected output
context konum Theme tema MediaQuery boyut
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does BuildContext represent?
- Widget's color
- Widget's size
- Widget's name
- Widget's position in the tree Correct answer
Explanation: BuildContext represents the widget's position in the widget tree and provides access to ancestral data.
2 Reach theme via context
final tema = ____.of(context);
final tema = Theme.of(context);
Explanation: Theme.of(context) returns the nearest Material theme in the tree.
3 BuildContext concepts
| Term | Meaning |
|---|---|
BuildContext |
Widget's position in the tree |
context |
Parameter of the build method |
ancestor |
Widget above in the tree |
Theme.of(context) |
Access to ancestral theme |