Flutter BuildContext 探究

6,778 阅读3分钟

0x00 前言

BuildContext是Flutter的重要部分,但是目前网上讲BuildContext的文章太少了,所以本篇文章讲讲BuildContext

0x01 BuildContext 介绍

BuildContext,顾名思义,Build(构建Widget) Context(应用上下文),就是构建Widget中的应用上下文。

所以BuildContext只出现在两个地方:

  1. StatelessWidget.build 方法中:创建StatelessWidget的build方法
  2. State对象中:一个是创建StatefulWidget的State对象的build方法中,另一个是State的成员变量

BuildContext实际是Element,BuildContext是为了阻止直接对Element操作而抽象出来的,所以BuildContextElement的抽象类,所有Element都继承自BuildContext

每一个Widget都有一个BuildContext

BuildContext是Widget在Widget树中位置的句柄。

0x02 访问 BuildContext 实例对象

BuildContextWidgetBulder(例如:StatelessWidget.build, State.build)方法传递;

BuildContext也是State的成员变量,在State内部,可以通过context直接访问

0x03 BuildContext 使用

BuildContext的作用主要是通过上下文获取指定的数据;

例如:Theme.of(context) 或者 showDialog(context: context,....)都需要BuildContext作为参数,这里的BuildContext就是调用这些方法的Widget的代表。

0x05 BuildContext 注意事项

每一个Widget都有一个BuildContext。假设有个A Widget,A Widget里肯定会有StatelessWidget.build或者State.build的build方法,build方法创建了 B Widget并返回,A Widget就是B Widget的父Widget,相应的, A Widget的BuildContext也是是B Widget 的BuildContext的父节点。

下面给一个例子加深理解:

@override
  Widget build(BuildContext context) {
    // here, Scaffold.of(context) returns null,
    //在Scaffold创建之前,如果在这里调用Scaffold.of(context)会返回null,是因为此时Scaffo//ld还没创建,所以其BuildContext也没有创建,为了在创建Scaffold的时候就取到他的BuildC//ontext,要使用Builder
    return Scaffold(
      appBar: AppBar(title: Text('Demo')),
      body: Builder(
        builder: (BuildContext context) {
          return FlatButton(
            child: Text('BUTTON'),
            onPressed: () {
              // here, Scaffold.of(context) returns the locally created Scaffold
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text('Hello.')
              ));
            }
          );
        }
      )
    );
  }

0x04 BuildContext 内部方法解析

为什么BuildContext可以用来获取上下文的数据,主要是因为BuildContext具有的以下方法:

  1. ancestorInheritedElementForWidgetOfExactType(Type targetType) → InheritedElement
Obtains the element corresponding to the nearest widget of the given type, which must be the type of a concrete InheritedWidget subclass. [...]
  1. ancestorRenderObjectOfType(TypeMatcher matcher) → RenderObject
Returns the RenderObject object of the nearest ancestor RenderObjectWidget widget that matches the given TypeMatcher. [...]
  1. ancestorStateOfType(TypeMatcher matcher) → State
Returns the State object of the nearest ancestor StatefulWidget widget that matches the given TypeMatcher. [...]
  1. ancestorWidgetOfExactType(Type targetType) → Widget
Returns the nearest ancestor widget of the given type, which must be the type of a concrete Widget subclass. [...]
  1. 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. [...]
  1. inheritFromElement(InheritedElement ancestor, { Object aspect }) → InheritedWidget
Registers this build context with ancestor such that when ancestor's widget changes this build context is rebuilt. [...]
  1. inheritFromWidgetOfExactType(Type targetType, { Object aspect }) → InheritedWidget
Obtains the nearest widget of the given type, 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. [...]
  1. rootAncestorStateOfType(TypeMatcher matcher) → State
Returns the State object of the furthest ancestor StatefulWidget widget that matches the given TypeMatcher. [...]
  1. 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. [...]
  1. visitChildElements(ElementVisitor visitor) → void
Walks the children of this widget. [...]

0x05 参考文献

docs.flutter.io/flutter/wid…