BuildContext class - widgets library (original) (raw)

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

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

BuildContext objects are passed to WidgetBuilder functions (such asStatelessWidget.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 Themewithin 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 Builderwidget can be used: the build context passed to the Builder.buildercallback will be that of the Builder itself.

For example, in the following snippet, the ScaffoldState.showBottomSheetmethod is called on the Scaffold widget that the build method itself creates. If a Builder had not been used, and instead the contextargument 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: AppBar(title: const Text('Demo')),
    body: Builder(
      builder: (BuildContext context) {
        return TextButton(
          child: const Text('BUTTON'),
          onPressed: () {
            Scaffold.of(context).showBottomSheet(
              (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.

Avoid storing instances of BuildContexts because they may become invalid if the widget they are associated with is unmounted from the widget tree. If a BuildContext is used across an asynchronous gap (i.e. after performing an asynchronous operation), consider checking mounted to determine whether the context is still valid before interacting with it:

  @override
  Widget build(BuildContext context) {
    return OutlinedButton(
      onPressed: () async {
        await Future<void>.delayed(const Duration(seconds: 1));
        if (context.mounted) {
          Navigator.of(context).pop();
        }
      },
      child: const Text('Delayed pop'),
    );
  }

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

Implementers

Constructors

BuildContext()

Properties

debugDoingBuildbool

Whether the widget is currently updating the widget or render tree.

no setter

hashCodeint

The hash code for this object.

no setterinherited

mountedbool

Whether the Widget this context is associated with is currently mounted in the widget tree.

no setter

ownerBuildOwner?

The BuildOwner for this context. The BuildOwner is in charge of managing the rendering pipeline for this context.

no setter

runtimeTypeType

A representation of the runtime type of the object.

no setterinherited

sizeSize?

The size of the RenderBox returned by findRenderObject.

no setter

widgetWidget

The current configuration of the Element that is this BuildContext.

no setter

Methods

dependOnInheritedElement(InheritedElement ancestor, {Object? aspect})→ InheritedWidget

Registers this build context with ancestor such that whenancestor's widget changes this build context is rebuilt.

dependOnInheritedWidgetOfExactType<T extends InheritedWidget>({Object? aspect})→ T?

Returns the nearest widget of the given type T and creates a dependency on it, or null if no appropriate widget is found.

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 Elementto 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 aRenderObjectWidget, this is the render object that the widget created for itself. Otherwise, it is the render object of the first descendantRenderObjectWidget.

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.

getInheritedWidgetOfExactType<T extends InheritedWidget>()→ T?

Returns the nearest widget of the given InheritedWidget subclass T or null if an appropriate ancestor is not found.

noSuchMethod(Invocation invocation)→ dynamic

Invoked when a nonexistent method or property is accessed.

inherited

toString()→ String

A string representation of this object.

inherited

visitAncestorElements(ConditionalElementVisitor visitor)→ void

Walks the ancestor chain, starting with the parent of this build context's widget, invoking the argument for each ancestor.

visitChildElements(ElementVisitor visitor)→ void

Walks the children of this widget.

Operators

operator ==(Object other)→ bool

The equality operator.

inherited