Interacting with BuildContext in the right place, at the right time
So far, we have indirectly mentioned BuildContext
here and there, but we have never really given it the attention it deserves. And it deserves a lot because BuildContext
is a crucial and fundamental concept of the Flutter framework. So, let’s take a closer look at what it is, how to use it, and what its role is in state management. You can find the full source code here: https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart.
What is BuildContext?
There are two main cases where we interact with BuildContext
. First, it is used in the build
method of a widget (Widget build(BuildContext context
), where it is passed as a parameter. We mainly use the context from this method to access inherited widgets such as MediaQuery
. Essentially, we need the context to locate widgets in the widget tree. Now, let’s take a closer look at the source code for BuildContext
: