Flutter BuildContext 探究

0x00 前言

BuildContext是Flutter的重要部分,可是目前網上講BuildContext的文章太少了,因此本篇文章講講BuildContexthtml

0x01 BuildContext 介紹

BuildContext,顧名思義,Build(構建Widget) Context(應用上下文),就是構建Widget中的應用上下文。bash

因此BuildContext只出如今兩個地方:app

  1. StatelessWidget.build 方法中:建立StatelessWidget的build方法
  2. State對象中:一個是建立StatefulWidget的State對象的build方法中,另外一個是State的成員變量

BuildContext實際是Element,BuildContext是爲了阻止直接對Element操做而抽象出來的,因此BuildContextElement的抽象類,全部Element都繼承自BuildContextless

每個Widget都有一個BuildContextide

BuildContext是Widget在Widget樹中位置的句柄。ui

0x02 訪問 BuildContext 實例對象

BuildContextWidgetBulder(例如:StatelessWidget.build, State.build)方法傳遞;this

BuildContext也是State的成員變量,在State內部,能夠經過context直接訪問spa

0x03 BuildContext 使用

BuildContext的做用主要是經過上下文獲取指定的數據;rest

例如:Theme.of(context) 或者 showDialog(context: context,....)都須要BuildContext做爲參數,這裏的BuildContext就是調用這些方法的Widget的表明。code

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…

相關文章
相關標籤/搜索