一、Scoped_model 簡介
A set of utilities that allow you to easily pass a data Model from a parent Widget down to its descendants. In addition, it also rebuilds all of the children that use the model when the model is updated. This library was originally extracted from the Fuchsia codebase.
Scoped_model 是一個 dart 第三方庫,提供了讓開發(fā)者能夠輕松地將數(shù)據(jù)模型從父 Widget 傳遞到它的后代的功能。此外,它還會在模型更新時重新渲染使用該模型的所有子項。
它直接來自于 Google 正在開發(fā)的新系統(tǒng) Fuchsia 中的核心 Widgets 中對 Model 類的簡單提取,作為獨立使用的獨立 Flutter 插件發(fā)布。
Scoped_model 提供三個主要的類:
Model 類:開發(fā)者創(chuàng)建的 Model 需要繼承該類,并可以監(jiān)聽 Models 的變化。
ScopedModel 類:如果想要將 Model 下發(fā)到 Widget hierarchy,可以使用 ScopedModel Widget 對 Model 進行包裹。這會使得該 Widget的所有子孫節(jié)點可以使用該被包裹的 Model。
ScopedModelDescendant 類:開發(fā)者可以使用該類在 Widget 樹中尋找合適的 ScopedModel 。它還會在模型更新時重新渲染使用該模型的所有子項。
Scoped_model 基于 Flutter 的多種特性創(chuàng)建,包括:
-
Model 實現(xiàn)了
Listenable
接口-
AnimationController
和TextEditingController
同樣實現(xiàn)了Listenable
。
-
Model 使用
InheritedWidget
進行傳遞。當一個InheritedWidget
重建后,它將精準地重建所有以來該數(shù)據(jù)的 Widget。不需要管理訂閱。Scoped_model 使用
AnimatedBuilder
,當 model 發(fā)生變化時 Widget 通過高級選項來監(jiān)聽 Model 和InheritedWidget
的重建
二、示例
官方實例代碼:
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
void main() {
runApp(MyApp(
model: CounterModel(),
));
}
class MyApp extends StatelessWidget {
final CounterModel model;
const MyApp({Key key, @required this.model}) : super(key: key);
@override
Widget build(BuildContext context) {
// At the top level of our app, we'll, create a ScopedModel Widget. This
// will provide the CounterModel to all children in the app that request it
// using a ScopedModelDescendant.
return ScopedModel<CounterModel>(
model: model,
child: MaterialApp(
title: 'Scoped Model Demo',
home: CounterHome('Scoped Model Demo'),
),
);
}
}
// Start by creating a class that has a counter and a method to increment it.
//
// Note: It must extend from Model.
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
// First, increment the counter
_counter++;
// Then notify all the listeners.
notifyListeners();
}
}
class CounterHome extends StatelessWidget {
final String title;
CounterHome(this.title);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
// Create a ScopedModelDescendant. This widget will get the
// CounterModel from the nearest parent ScopedModel<CounterModel>.
// It will hand that CounterModel to our builder method, and
// rebuild any time the CounterModel changes (i.e. after we
// `notifyListeners` in the Model).
ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return Text(
model.counter.toString(),
style: Theme.of(context).textTheme.headline4,
);
},
),
],
),
),
// Use the ScopedModelDescendant again in order to use the increment
// method from the CounterModel
floatingActionButton: ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return FloatingActionButton(
onPressed: model.increment,
tooltip: 'Increment',
child: Icon(Icons.add),
);
},
),
);
}
}
三、實現(xiàn)原理
Scoped model使用了觀察者模式,將數(shù)據(jù)模型放在父代,后代通過找到父代的model進行數(shù)據(jù)渲染,最后數(shù)據(jù)改變時將數(shù)據(jù)傳回,父代再通知所有用到了該model的子代去更新狀態(tài)。
該框架實際上是利用InheritedWidget
實現(xiàn)數(shù)據(jù)的傳遞的。在下一小節(jié)中會對InheritedWidget
及其原理進行分析,讀者可以先閱讀下一節(jié)進行了解。
3.1 源碼分析
下面來分析 Scoped_model 的源碼和實現(xiàn)。
Model
abstract class Model extends Listenable {
final Set<VoidCallback> _listeners = Set<VoidCallback>();
int _version = 0;
int _microtaskVersion = 0;
/// [listener] will be invoked when the model changes.
@override
void addListener(VoidCallback listener) {
_listeners.add(listener);
}
/// [listener] will no longer be invoked when the model changes.
@override
void removeListener(VoidCallback listener) {
_listeners.remove(listener);
}
/// Returns the number of listeners listening to this model.
int get listenerCount => _listeners.length;
/// Should be called only by [Model] when the model has changed.
@protected
void notifyListeners() {
// We schedule a microtask to debounce multiple changes that can occur
// all at once.
if (_microtaskVersion == _version) {
_microtaskVersion++;
// Schedules a callback to be called before all other currently scheduled ones.
scheduleMicrotask(() {
_version++;
_microtaskVersion = _version;
_listeners.toList().forEach((VoidCallback listener) => listener());
});
}
}
}
Model
類很簡單,就是一個實現(xiàn)了Listenable
的抽象類,這里的核心方法就是notifyListeners
的實現(xiàn),這里使用了“微任務(wù)”來實現(xiàn)防抖動。
ScopedModel 構(gòu)造函數(shù)
class ScopedModel<T extends Model> extends StatelessWidget {
/// The [Model] to provide to [child] and its descendants.
final T model;
/// The [Widget] the [model] will be available to.
final Widget child;
ScopedModel({@required this.model, @required this.child})
: assert(model != null),
assert(child != null);
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: model,
builder: (context, _) => _InheritedModel<T>(model: model, child: child),
);
}
// 向外暴露方式
static T of<T extends Model>(
BuildContext context, {
bool rebuildOnChange = false,
}) {
Widget widget = rebuildOnChange
? context.dependOnInheritedWidgetOfExactType<_InheritedModel<T>>()
: context
.getElementForInheritedWidgetOfExactType<_InheritedModel<T>>()
?.widget;
if (widget == null) {
throw ScopedModelError();
} else {
return (widget as _InheritedModel<T>).model;
}
}
}
首先看一下of()
方法,該方法是用來向外/子類來暴露當前對象的,根據(jù) rebuildOnChange 有兩種返回方式:
dependOnInheritedWidgetOfExactType<_InheritedModel<T>>():該方法會注冊依賴關(guān)系。
getElementForInheritedWidgetOfExactType<_InheritedModel<T>>():該方法不會注冊依賴關(guān)系。
兩個方法的源碼如下:
@override
InheritedElement getElementForInheritedWidgetOfExactType<T extends InheritedWidget>() {
assert(_debugCheckStateIsActiveForAncestorLookup());
final InheritedElement ancestor = _inheritedWidgets == null ? null : _inheritedWidgets[T];
return ancestor;
}
@override
InheritedWidget dependOnInheritedWidgetOfExactType({ Object aspect }) {
assert(_debugCheckStateIsActiveForAncestorLookup());
final InheritedElement ancestor = _inheritedWidgets == null ? null : _inheritedWidgets[T];
//多出的部分
if (ancestor != null) {
assert(ancestor is InheritedElement);
return dependOnInheritedElement(ancestor, aspect: aspect) as T;
}
_hadUnsatisfiedDependencies = true;
return null;
}
我們可以看到,dependOnInheritedWidgetOfExactType()
比 getElementForInheritedWidgetOfExactType()
多調(diào)了dependOnInheritedElement
方法,dependOnInheritedElement
源碼如下:
@override
InheritedWidget dependOnInheritedElement(InheritedElement ancestor, { Object aspect }) {
assert(ancestor != null);
_dependencies ??= HashSet<InheritedElement>();
_dependencies.add(ancestor);
ancestor.updateDependencies(this, aspect);
return ancestor.widget;
}
可以看到dependOnInheritedElement
方法中主要是注冊了依賴關(guān)系,也就是說,調(diào)用dependOnInheritedWidgetOfExactType()
和 getElementForInheritedWidgetOfExactType()
的區(qū)別就是前者會注冊依賴關(guān)系,而后者不會,所以在調(diào)用dependOnInheritedWidgetOfExactType()
時,InheritedWidget
和依賴它的子孫組件關(guān)系便完成了注冊,之后當InheritedWidget
發(fā)生變化時,就會更新依賴它的子孫組件,也就是會調(diào)這些子孫組件的didChangeDependencies()
方法和build()
方法。而當調(diào)用的是 getElementForInheritedWidgetOfExactType()
時,由于沒有注冊依賴關(guān)系,所以之后當InheritedWidget
發(fā)生變化時,就不會更新相應(yīng)的子孫Widget。文章的后面會專門對InheritedWidget
進行分析。
再來看build
的實現(xiàn),該方法返回了可以處理動畫的AnimatedBuilder
,其中 builder 類型為 _InheritedModel
,該類源碼如下:
class _InheritedModel<T extends Model> extends InheritedWidget {
final T model;
final int version;
_InheritedModel({Key key, Widget child, T model})
: this.model = model,
this.version = model._version,
super(key: key, child: child);
// 該回調(diào)決定當 data 發(fā)生變化時,是否通知子樹中依賴 data 的 Widget
@override
bool updateShouldNotify(_InheritedModel<T> oldWidget) =>
(oldWidget.version != version);
}
代碼很簡單,就是通過實現(xiàn)updateShouldNotify
來否通知子樹中依賴 data 的 Widget。
ScopedModelDescendant
/// Builds a child for a [ScopedModelDescendant].
typedef Widget ScopedModelDescendantBuilder<T extends Model>(
BuildContext context,
Widget child,
T model,
);
class ScopedModelDescendant<T extends Model> extends StatelessWidget {
/// Builds a Widget when the Widget is first created and whenever
/// the [Model] changes if [rebuildOnChange] is set to `true`.
final ScopedModelDescendantBuilder<T> builder;
/// An optional constant child that does not depend on the model. This will
/// be passed as the child of [builder].
final Widget child;
/// An optional value that determines whether the Widget will rebuild when
/// the model changes.
final bool rebuildOnChange;
/// Creates the ScopedModelDescendant
ScopedModelDescendant({
@required this.builder,
this.child,
this.rebuildOnChange = true,
});
@override
Widget build(BuildContext context) {
return builder(
context,
child,
ScopedModel.of<T>(context, rebuildOnChange: rebuildOnChange),
);
}
}
開發(fā)者可以使用該類在 Widget 樹中尋找合適的 ScopedModel,其實是通過 ScopedModel
的of()
方法來獲取合適的 InheritedWidget
。
到這里 Scoped_model 源碼和實現(xiàn)就分析完了,其實就是利用InheritedWidget
來實現(xiàn)數(shù)據(jù)的層層下發(fā),下面就來分析該類。
3.2 InheritedWidget 原理分析
InheritedWidget
是Flutter中非常重要的一個功能型組件,它提供了一種數(shù)據(jù)在 widget 樹中從上到下傳遞、共享的方式,比如我們在應(yīng)用的根widget中通過InheritedWidget
共享了一個數(shù)據(jù),那么我們便可以在任意子 widget 中來獲取該共享的數(shù)據(jù)。
這個特性在一些需要在 widge t樹中共享數(shù)據(jù)的場景中非常方便,如 Flutter SDK 中正是通過 InheritedWidget 來共享應(yīng)用主題(Theme
)和 Locale (當前語言環(huán)境)信息的。
3.2.1 InheritedWidget 的使用方法
先看一個InheritedWidget
最簡單的使用示例:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyWelcomeInfo extends InheritedWidget {
MyWelcomeInfo({Key key, this.welcomeInfo, Widget child})
: super(key: key, child: child);
final String welcomeInfo;
// 該回調(diào)決定當 data 發(fā)生變化時,是否通知子樹中依賴 data 的 Widget
@override
bool updateShouldNotify(InheritedWidget oldWidget) {
return oldWidget.welcomeInfo != welcomeInfo;
}
}
class MyNestedChild extends StatelessWidget {
@override
build(BuildContext context) {
// 通過 inheritFromWidgetOfExactType 獲取 InheritedWidget
final MyWelcomeInfo widget =
context.inheritFromWidgetOfExactType(MyWelcomeInfo);
return Text(widget.welcomeInfo);
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter InheritWidget',
home: MyWelcomeInfo(
welcomeInfo: 'hello flutter',
child: Center(
child: MyNestedChild(),
)),
);
}
}
可以看出我們使用InheritedWidget
時涉及到的工作量主要有 2 部分:
創(chuàng)建一個繼承自
InheritedWidget
的類,并將其插入 Widget 樹通過 BuildContext 對象提供的
inheritFromWidgetOfExactType
方法查找 Widget 樹中最近的一個特定類型的InheritedWidget
類的實例
這里還暗含了一個邏輯,那就是當通過 inheritFromWidgetOfExactType
查找特定類型InheritedWidget
時,InheritedWidget
的信息是由父元素層層向子元素傳遞下來?還是 inheritFromWidgetOfExactType
方法自己層層向上查找呢?
接下來讓我們從源碼的角度分別看看 Flutter 框架對以上幾部分的實現(xiàn)。
3.2.2 原理分析
InheritedWidget 源碼如下:
abstract class InheritedWidget extends ProxyWidget {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const InheritedWidget({ Key key, Widget child })
: super(key: key, child: child);
@override
InheritedElement createElement() => InheritedElement(this);
/// Whether the framework should notify widgets that inherit from this widget.
///
/// When this widget is rebuilt, sometimes we need to rebuild the widgets that
/// inherit from this widget but sometimes we do not. For example, if the data
/// held by this widget is the same as the data held by `oldWidget`, then we
/// do not need to rebuild the widgets that inherited the data held by
/// `oldWidget`.
///
/// The framework distinguishes these cases by calling this function with the
/// widget that previously occupied this location in the tree as an argument.
/// The given widget is guaranteed to have the same [runtimeType] as this
/// object.
@protected
bool updateShouldNotify(covariant InheritedWidget oldWidget);
}
它是一個繼承自 ProxyWidget
的抽象類。內(nèi)部沒什么邏輯,除了實現(xiàn)了一個 createElement
方法之外,還定義了一個 updateShouldNotify()
接口。 每次當InheritedElement
的實例更新時會執(zhí)行該方法并傳入更新之前對應(yīng)的 Widget 對象,如果該方法返回 true
那么依賴該 Widget 的(在 build 階段通過 inheritFromWidgetOfExactType
方法查找過該 Widget 的子 widget)實例會被通知進行更新;如果返回 false
則不會通知依賴項更新。
3.2.3 InheritedWidget 相關(guān)信息的傳遞機制
每個 Element 實例上都有一個 _inheritedWidgets
屬性。該屬性的類型為:
Map<Type, InheritedElement> _inheritedWidgets;
其中保存了祖先節(jié)點中出現(xiàn)的InheritedWidget
與其對應(yīng) element 的映射關(guān)系。在 element 的 mount
階段和 active
階段,會執(zhí)行 _updateInheritance()
方法更新這個映射關(guān)系。
普通 Element 實例
對于普通 Element 實例,_updateInheritance()
只是單純把父 element 的 _inheritedWidgets
屬性保存在自身 _inheritedWidgets
里。從而實現(xiàn)映射關(guān)系的層層向下傳遞。
void _updateInheritance() {
assert(_active);
_inheritedWidgets = _parent?._inheritedWidgets;
}
InheritedElement
由InheritedWidget
創(chuàng)建的InheritedElement
重寫了該方法:
void _updateInheritance() {
assert(_active);
final Map<Type, InheritedElement> incomingWidgets = _parent?._inheritedWidgets;
if (incomingWidgets != null)
_inheritedWidgets = new HashMap<Type, InheritedElement>.from(incomingWidgets);
else
_inheritedWidgets = new HashMap<Type, InheritedElement>();
_inheritedWidgets[widget.runtimeType] = this;
}
可以看出 InheritedElement
實例會把自身的信息添加到 _inheritedWidgets
屬性中,這樣其子孫 element 就可以通過前面提到的 _inheritedWidgets
的傳遞機制獲取到此 InheritedElement
的引用。
3.2.4 InheritedWidget 的更新通知機制
從前問可知_inheritedWidgets
屬性存在于 Element 實例上,而代碼中調(diào)用的 inheritFromWidgetOfExactType
方法則存在于 BuildContext
實例之上。那么BuildContext
是如何獲取 Element 實例上的信息的呢?答案是不需要獲取。因為每一個 Element 實例也都是一個 BuildContext 實例。這一點可以從 Element 的定義中得到:
abstract class Element extends DiagnosticableTree implements BuildContext {
...
}
而每次 Element 實例執(zhí)行 Widget 實例的 build
方法時傳入的 context 就是該 Element 實例自身,以 StatelessElement 為例:
class StatelessElement extends ComponentElement {
...
@override
Widget build() => widget.build(this);
...
}
既然可以拿到 InheritedWidget
的信息了,接下來通過源碼看看更新通知機制的具體實現(xiàn)。
首先看一下 inheritFromWidgetOfExactType
的實現(xiàn):
@override
InheritedWidget inheritFromWidgetOfExactType(Type targetType, { Object aspect }) {
...
// 獲取實例
final InheritedElement ancestor = _inheritedWidgets == null ? null : _inheritedWidgets[targetType];
if (ancestor != null) {
assert(ancestor is InheritedElement);
// 添加到依賴項列表
return inheritFromElement(ancestor, aspect: aspect);
}
_hadUnsatisfiedDependencies = true;
return null;
}
首先在 _inheritedWidget
映射中查找是否有特定類型 InheritedWidget
的實例。如果有則將該實例添加到自身的依賴列表中,同時將自身添加到對應(yīng)的依賴項列表中。這樣該 InheritedWidget 在更新后就可以通過其 _dependents
屬性知道需要通知哪些依賴了它的 widget。
每當 InheritedElement
實例更新時,會執(zhí)行實例上的 notifyClients
方法通知依賴了它的子 element 同步更新。notifyClients
實現(xiàn)如下:
void notifyClients(InheritedWidget oldWidget) {
if (!widget.updateShouldNotify(oldWidget))
return;
assert(_debugCheckOwnerBuildTargetExists('notifyClients'));
for (Element dependent in _dependents) {
assert(() {
// check that it really is our descendant
Element ancestor = dependent._parent;
while (ancestor != this && ancestor != null)
ancestor = ancestor._parent;
return ancestor == this;
}());
// check that it really depends on us
assert(dependent._dependencies.contains(this));
dependent.didChangeDependencies();
}
}
首先執(zhí)行相應(yīng) InheritedWidget
上的 updateShouldNotify
方法判斷是否需要通知,如果該方法返回 true
則遍歷 _dependents
列表中的 element 并執(zhí)行他們的 didChangeDependencies()
方法。這樣 InheritedWidget
中的更新就通知到依賴它的子 widget 中了。
@mustCallSuper
void didChangeDependencies() {
assert(_active); // otherwise markNeedsBuild is a no-op
assert(_debugCheckOwnerBuildTargetExists('didChangeDependencies'));
//
markNeedsBuild();
}
參考
Flutter | 狀態(tài)管理探索篇——Scoped Model
Flutter實戰(zhàn)-第七章 功能型組件
從 Flutter 源碼看 InheritedWidget 內(nèi)部實現(xiàn)原理