BuildContext class Null safety

A handle to the location of a widget in the widget tree.

This class presents a set of methods that can be used from StatelessWidget.build methods and from methods on State objects.

BuildContext objects are passed to WidgetBuilder functions (such as StatelessWidget.build), and are available from the State.context member. Some static functions (e.g. showDialog, Theme.of, and so forth) also take build contexts so that they can act on behalf of the calling widget, or obtain data specifically for the given context.

Each widget has its own BuildContext, which becomes the parent of the widget returned by the StatelessWidget.build or State.build function. (And similarly, the parent of any children for RenderObjectWidgets.)

In particular, this means that within a build method, the build context of the widget of the build method is not the same as the build context of the widgets returned by that build method. This can lead to some tricky cases. For example, Theme.of(context) looks for the nearest enclosing Theme of the given build context. If a build method for a widget Q includes a Theme within its returned widget tree, and attempts to use Theme.of passing its own context, the build method for Q will not find that Theme object. It will instead find whatever Theme was an ancestor to the widget Q. If the build context for a subpart of the returned tree is needed, a Builder widget can be used: the build context passed to the Builder.builder callback will be that of the Builder itself.

For example, in the following snippet, the ScaffoldState.showBottomSheet method is called on the Scaffold widget that the build method itself creates. If a Builder had not been used, and instead the context argument of the build method itself had been used, no Scaffold would have been found, and the Scaffold.of function would have returned null.

@override
Widget build(BuildContext context) {
  // here, Scaffold.of(context) returns null
  return Scaffold(
    appBar: const AppBar(title: Text('Demo')),
    body: Builder(
      builder: (BuildContext context) {
        return TextButton(
          child: const Text('BUTTON'),
          onPressed: () {
            Scaffold.of(context).showBottomSheet<void>(
              (BuildContext context) {
                return Container(
                  alignment: Alignment.center,
                  height: 200,
                  color: Colors.amber,
                  child: Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        const Text('BottomSheet'),
                        ElevatedButton(
                          child: const Text('Close BottomSheet'),
                          onPressed: () {
                            Navigator.pop(context),
                          },
                        )
                      ],
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    )
  );
}

The BuildContext for a particular widget can change location over time as the widget is moved around the tree. Because of this, values returned from the methods on this class should not be cached beyond the execution of a single synchronous function.

BuildContext objects are actually Element objects. The BuildContext interface is used to discourage direct manipulation of Element objects.

Implementers

Constructors

BuildContext()

Properties

debugDoingBuild bool
Whether the widget is currently updating the widget or render tree.
read-only
hashCode int
The hash code for this object.
read-onlyinherited
owner BuildOwner?
The BuildOwner for this context. The BuildOwner is in charge of managing the rendering pipeline for this context.
read-only
runtimeType Type
A representation of the runtime type of the object.
read-onlyinherited
size Size?
The size of the RenderBox returned by findRenderObject.
read-only
widget Widget
The current configuration of the Element that is this BuildContext.
read-only

Methods

dependOnInheritedElement(InheritedElement ancestor, {Object aspect}) InheritedWidget
Registers this build context with ancestor such that when ancestor's widget changes this build context is rebuilt.
dependOnInheritedWidgetOfExactType<T extends InheritedWidget>({Object? aspect}) → T?
Obtains the nearest widget of the given type T, which must be the type of a concrete InheritedWidget subclass, and registers this build context with that widget such that when that widget changes (or a new widget of that type is introduced, or the widget goes away), this build context is rebuilt so that it can obtain new values from that widget.
describeElement(String name, {DiagnosticsTreeStyle style = DiagnosticsTreeStyle.errorProperty}) DiagnosticsNode
Returns a description of the Element associated with the current build context.
describeMissingAncestor({required Type expectedAncestorType}) List<DiagnosticsNode>
Adds a description of a specific type of widget missing from the current build context's ancestry tree.
describeOwnershipChain(String name) DiagnosticsNode
Adds a description of the ownership chain from a specific Element to the error report.
describeWidget(String name, {DiagnosticsTreeStyle style = DiagnosticsTreeStyle.errorProperty}) DiagnosticsNode
Returns a description of the Widget associated with the current build context.
dispatchNotification(Notification notification) → void
Start bubbling this notification at the given build context.
findAncestorRenderObjectOfType<T extends RenderObject>() → T?
Returns the RenderObject object of the nearest ancestor RenderObjectWidget widget that is an instance of the given type T.
findAncestorStateOfType<T extends State<StatefulWidget>>() → T?
Returns the State object of the nearest ancestor StatefulWidget widget that is an instance of the given type T.
findAncestorWidgetOfExactType<T extends Widget>() → T?
Returns the nearest ancestor widget of the given type T, which must be the type of a concrete Widget subclass.
findRenderObject() RenderObject?
The current RenderObject for the widget. If the widget is a RenderObjectWidget, this is the render object that the widget created for itself. Otherwise, it is the render object of the first descendant RenderObjectWidget.
findRootAncestorStateOfType<T extends State<StatefulWidget>>() → T?
Returns the State object of the furthest ancestor StatefulWidget widget that is an instance of the given type T.
getElementForInheritedWidgetOfExactType<T extends InheritedWidget>() InheritedElement?
Obtains the element corresponding to the nearest widget of the given type T, which must be the type of a concrete InheritedWidget subclass.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a non-existent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited
visitAncestorElements(bool visitor(Element element)) → void
Walks the ancestor chain, starting with the parent of this build context's widget, invoking the argument for each ancestor. The callback is given a reference to the ancestor widget's corresponding Element object. The walk stops when it reaches the root widget or when the callback returns false. The callback must not return null.
visitChildElements(ElementVisitor visitor) → void
Walks the children of this widget.

Operators

operator ==(Object other) bool
The equality operator.
inherited