Middle
What is BuildContext in Flutter and how is it used?
sobes.tech AI
Answer from AI
BuildContext is a handle that points to the location of a widget in the widget tree. Each widget has its own BuildContext.
It is used:
- To access data from ancestors: For example,
Theme.of(context)to get the current theme. - To find ancestor widgets:
Navigator.of(context)for navigation. - To perform context-dependent actions: Displaying a
SnackBarviaScaffoldMessenger.of(context). - To get the size and position of a widget: Using
BuildContext.sizeorBuildContext.findRenderObject().
Example:
// Accessing ThemeData
ThemeData theme = Theme.of(context);
// Navigation
Navigator.push(
context,
MaterialPageRoute(builder: (context) => NextScreen()),
);
// Displaying SnackBar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Hello')),
);
BuildContext is only valid during the lifecycle of the corresponding widget.