Flutter BuildContext

| Page Views: 98

Flutter BuildContext Tutorial

In this tutorial we want to look at and explain an important class we will be using in each and every one of flutter applications, the BuildContext.

What is BuildContext?

BuildContext is an abstract class acting as a handle to the location of a widget in the widget tree.

abstract class BuildContext

It's defined in the flutter package.

It's role as an abstract class is to hold a set of methods. These methods can be used from StatelessWidget.build methods and from methods on State objects.

Normally when you are using widget builder functions like the build() method of the StatelessWidget class.

For instance here's a BuildContext object being passed to the build() method of a StatelessWidget subclass:

 @override
  Widget build(BuildContext context) {
    return MaterialApp()

Most components in Flutter are widgets. And these widgets, each of them, has it's own BuildContext. This BuildContext object will be used as the parent of the widget that is returned by the StatelessWidget.build() or the State.build() method.

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

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post