What does BuildContext do in Flutter

What does BuildContext do in Flutter?

While designing and developing a flutter mobile application we might have used BuildContext many times. So in this article, we will go through what does BuildContext does in Flutter.

What does BuildContext do in Flutter?

BuildContext is, like its name is implying, the context in which a specific widget is built. Generally speaking, there are 2 use cases for context :

  • Interact with your parents (get/post data mostly)
  • Once rendered on screen, get your screen size and position

The second point is kinda rare. On the other hand, the first point is used nearly everywhere.

For example, when you want to push a new route, you’ll do Navigator. of(context).pushNamed(‘myRoute’).

Notice the context here. It’ll be used to get the closest instance of the NavigatorState widget above in the tree. Then call the method pushNamed on that instance.

When to use BuildContext?

BuildContext is really useful when you want to pass data downward without having to manually assign it to every widgets’ configuration for example; you’ll want to access them everywhere. But you don’t want to pass it on to every single constructor.

You could potentially make a global or a singleton, but then when confs change your widgets won’t automatically rebuild.

In this case, you use InheritedWidget. with it you could potentially write the following :

class Configuration extends InheritedWidget {
  final String myConf;

  const Configuration({this.myConf, Widget child}): super(child: child);

  @override
  bool updateShouldNotify(Configuration oldWidget) {
    return myConf != oldWidget.myConf;
  }
}

And then, use it this way :

void main() {
  runApp(
    new Configuration(
      myConf: "Hello world",
      child: new MaterialApp(
        // usual stuff here
      ),
    ),
  );
}

Now everywhere inside your app, you can access these configs using the BuildContext like below:

final configuration = context.inheritFromWidgetOfExactType(Configuration);

We can also say that BuildContext Class is nothing else but a reference to the location of a widget within the tree structure of all the widgets which are built.

Every flutter widget has an @override build() method with the argument of BuildContext.

class ContextTestWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {.....}
}

Simply explain is that the BuildContext is:

  • A BuildContext only belongs to one widget.
  • BuildContext objects are passed to WidgetBuilder functions
    A BuildContext only belongs to one widget.

If a widget ‘A’ has children’s widgets, the BuildContext of widget ‘A’ will become the parent BuildContext of the direct children BuildContexts.

Reading this, it is clear that BuildContexts are chained and are composing a tree of BuildContexts.

There are two types of widget

  • Class widget context (parent widget)
  • Build widget context (child widget)

1. Class widget context – This context is not visible for us, It’s only used by the framework itself for creating element tree.

2. Build widget context – This context is visible for us, Its use by the framework, and also we use it for some purposes eg:- for accessing the ancestor widget.

build widget context / BuildContext context

now, build widget context is the context type that you passed for build() method.

@override
Widget build(BuildContext context) {            //BuildContext
  return Text(
    'Example',
    style: Theme.of(context).textTheme.title,
  );
}

Where is the location of that widget?

To get an answer to the above question considers a code snippet like the below:

@override
Widget build(BuildContext context) {
  //here is the location of this child widget is build.
  return Text(
    'Example',
    style: Theme.of(context).textTheme.title,
  );
}

Consider a code snippet like the below:

@override
  Widget build(BuildContext context) {
    // here build location of that widget                     //here
    return Scaffold(
      appBar: AppBar(title: Text('Demo')),
      body: Builder(
        // here build location of that widget                 //here
        builder: (BuildContext context) {
          return FlatButton(
            child: Text('BUTTON'),
            onPressed: () {
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text('Hello.')
              ));
            }
          );
        }
      )
    );

Conclusion:

Thanks for being with us on a Flutter Journey.

So in this article, we have been through what does BuildContext does in Flutter.

Keep Learning !!! Keep Fluttering !!!

Still, need Support for Flutter Development? Do let us know.

Dive into the world of Flutter with FlutterAgency’s awesome resources.

Ready to take your Flutter development to the next level? Buckle up and join  at FlutterAgency.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

✓ Valid number ✕ Invalid number

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number