Builder Widget and Contexts in Flutter

Tushar Upadhyay
2 min readMar 19, 2020

Before Moving to this question , First i want to tell you about contexts in Flutter

As we know almost every thing in Flutter is a Widget .. This forms a tree like structure which we call a Widget Tree.. but how Flutter keeps track of the reference to our position in a widget tree? Here comes the use of a context

In every statefull or stateless widget we define a build method which takes an argument BuildContext , this context is simply the reference to its Parent widget .. That means it is the context of its parent widget in a widget tree

Now coming to our question , What are Builders in Flutter?

As far we know that the BuildContext , we pass are the contexts of the parent widget but what if we want to use the context to same widget ? Fortunately we have Builders in Flutter which Provides us the contexts of the same widget we working on…

But why and when we need the context ofthe same widget?

Let’s make a drawer

class DrawerExample extends StatefulWidget {
@override
_DrawerExampleState createState() => _DrawerExampleState();
}
class _DrawerExampleState extends State<DrawerExample> {
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
);
}}

We can open the drawer by swiping from left in Android and Ios

But in some case if we want to open it by a button then how can we do it?

Fortunately in Flutter , it provides a method in Scaffold class named openDrawer() to open the Drawer.

So you must be thinking about creating a button widget and in onPress method we call Scaffold.of(context).openDrawer() right?

but if you do this nothing will happen and the drawer will not open..But why?

as you can see the of method requires a context to the scaffold class but we provided the context to the root widget ..

One of the ways to do this is to make use of Global keys but this isn’t our topic right now.

Another way to implement this by making the use of the Builder Class

Builder class provides us a Callback function which provides us a context of the same widget (i.e. of Scaffold in this case)

We can use this context to call caffold.of(context).openDrawer()

this time our code works and the drawer opens!

--

--