導航
前言
MobX是前端一個很流行的函式響應式程式設計,讓狀態變得簡單可擴充套件。背後的哲學是:
任何源自應用狀態的東西都應該自動地獲得
基於觀察者的MVVM框架完成了資料到UI的雙向繫結。Google2017年也釋出了類似思想的MVVM框架ViewModel。MVVM是資料驅動更新的框架,可以很方便地把頁面和邏輯抽開,在前端很受歡迎。所以MobX也出了dart的版本用來支援Flutter的使用。下面我們就開始動手在Flutter引入MobX。
使用
先放出官網,使用分幾步走:
1. 首先,引入依賴:
mobx: ^0.2.0
flutter_mobx: ^0.2.0
mobx_codegen: ^0.2.0
複製程式碼
2. 新增一個store:
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
// 自動生成的類
part 'settings_store.g.dart';
class SettingsStore = _SettingsStore with _$SettingsStore;
abstract class _SettingsStore implements Store {
var key = {
"showPage":"showPage",
};
@observable
String showPage = "";
@action
getPrefsData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
showPage = prefs.get(key["showPage"]) ?? "首頁";
}
@action
saveShowPage(String showPage) async {
if(showPage == null) {
return;
}
this.showPage = showPage;
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(key["showPage"], showPage);
}
}
複製程式碼
對於dart版本的mobx,是通過生成新的類來實現雙向繫結的效果,所以需要在store裡面加上生成類的一些定義:
part 'settings_store.g.dart';
class SettingsStore = _SettingsStore with _$SettingsStore;
複製程式碼
_$SettingsStore是待生成的類,SettingsStore則是混合了兩個store的新類。如下是自動生成的類:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'settings_store.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars
mixin _$SettingsStore on _SettingsStore, Store {
final _$showPageAtom = Atom(name: '_SettingsStore.showPage');
@override
String get showPage {
_$showPageAtom.reportObserved();
return super.showPage;
}
@override
set showPage(String value) {
_$showPageAtom.context.checkIfStateModificationsAreAllowed(_$showPageAtom);
super.showPage = value;
_$showPageAtom.reportChanged();
}
final _$getPrefsDataAsyncAction = AsyncAction('getPrefsData');
@override
Future getPrefsData() {
return _$getPrefsDataAsyncAction.run(() => super.getPrefsData());
}
final _$saveShowPageAsyncAction = AsyncAction('saveShowPage');
@override
Future saveShowPage(String showPage) {
return _$saveShowPageAsyncAction.run(() => super.saveShowPage(showPage));
}
}
複製程式碼
要實現上面的效果還需要分幾步走:
-
在需要被觀察的資料增加@observable註解,需要執行操作的方法增加@action註解,
-
接著執行
flutter packages pub run build_runner build
-
就會自動生成上述的類,特別的是,如果需要實時跟蹤store的變化從而實時改變新生成的類,需要執行一個命令:
flutter packages pub run build_runner watch
, 如果操作失敗了,可以嘗試下面的clean命令:flutter packages pub run build_runner watch --delete-conflicting-outputs
3. 在widget中使用:
在需要觀察資料變化的widget套上一層Observer widget,
_buildShowPageLine(BuildContext context) {
return GestureDetector(
onTap: () {
showDialog<String>(
context: context,
builder: (context) {
String selectValue = '${settingsStore.showPage}';
List<String> valueList = ["首頁", "生活"];
return RadioAlertDialog(title: "選擇展示頁面",
selectValue: selectValue,
valueList: valueList);
}).then((value) {
print(value);
settingsStore.saveShowPage(value);
});
},
// 在需要觀察變化的widget套上一層Observer widget,
child: Observer(
builder: (_) => ListTile(
title: Common.primaryTitle(content: "預設展示頁面"),
subtitle: Common.primarySubTitle(content: '${settingsStore.showPage}'),
)
));
}
複製程式碼
完成上述步驟就可以通過對store的資料進行操作,從而自動重新整理widget。
原理
看完上述的使用之後,相信讀者會感到又疑惑又神奇。別急,接下來就進入原理的剖析。
首先看到新生成的程式碼_$SettingsStore,其中有幾處關鍵的插樁程式碼,
@override
String get showPage {
_$showPageAtom.reportObserved();
return super.showPage;
}
@override
set showPage(String value) {
_$showPageAtom.context.checkIfStateModificationsAreAllowed(_$showPageAtom);
super.showPage = value;
_$showPageAtom.reportChanged();
}
複製程式碼
可以看到在獲取變數時,會呼叫dart reportObserved()
, 設定變數會呼叫dart reportChanged
, 從名字就可以看出獲取變數就是將變數上報,變為被觀察的狀態,設定變數其實就是上報資料變化,進行通知。
我們先看看reportObserved()做了什麼,
// atom可以理解為對應的被觀察變數的封裝
void _reportObserved(Atom atom) {
final derivation = _state.trackingDerivation;
if (derivation != null) {
derivation._newObservables.add(atom);
if (!atom._isBeingObserved) {
atom
.._isBeingObserved = true
.._notifyOnBecomeObserved();
}
}
}
複製程式碼
可以看出核心就是把當前的變數加入被觀察的佇列中去。
reportChanged做的是啥呢,
void propagateChanged(Atom atom) {
if (atom._lowestObserverState == DerivationState.stale) {
return;
}
atom._lowestObserverState = DerivationState.stale;
for (final observer in atom._observers) {
if (observer._dependenciesState == DerivationState.upToDate) {
observer._onBecomeStale();
}
observer._dependenciesState = DerivationState.stale;
}
}
複製程式碼
關鍵的程式碼是
if (observer._dependenciesState == DerivationState.upToDate) {
observer._onBecomeStale();
}
複製程式碼
當資料需要更新的時候,呼叫觀察者的_onBecomeStale方法,看到這裡,相信聰明的讀者應該會記起觀察者的存在了。 那就是我們用了被觀察資料的widget上面套著的Observer的widget。原始碼如下:
library flutter_mobx;
// ignore_for_file:implementation_imports
import 'package:flutter/widgets.dart';
import 'package:mobx/mobx.dart';
import 'package:mobx/src/core.dart' show ReactionImpl;
/// Observer observes the observables used in the `builder` function and rebuilds the Widget
/// whenever any of them change. There is no need to do any other wiring besides simply referencing
/// the required observables.
///
/// Internally, [Observer] uses a `Reaction` around the `builder` function. If your `builder` function does not contain
/// any observables, [Observer] will throw an [AssertionError]. This is a debug-time hint to let you know that you are not observing any observables.
class Observer extends StatefulWidget {
/// Returns a widget that rebuilds every time an observable referenced in the
/// [builder] function is altered.
///
/// The [builder] argument must not be null. Use the [context] to specify a ReactiveContext other than the `mainContext`.
/// Normally there is no need to change this. [name] can be used to give a debug-friendly identifier.
const Observer({@required this.builder, Key key, this.context, this.name})
: assert(builder != null),
super(key: key);
final String name;
final ReactiveContext context;
final WidgetBuilder builder;
@visibleForTesting
Reaction createReaction(Function() onInvalidate) {
final ctx = context ?? mainContext;
return ReactionImpl(ctx, onInvalidate,
name: name ?? 'Observer@${ctx.nextId}');
}
@override
State<Observer> createState() => _ObserverState();
void log(String msg) {
debugPrint(msg);
}
}
class _ObserverState extends State<Observer> {
ReactionImpl _reaction;
@override
void initState() {
super.initState();
_reaction = widget.createReaction(_invalidate);
}
void _invalidate() => setState(noOp);
static void noOp() {}
@override
Widget build(BuildContext context) {
Widget built;
dynamic error;
_reaction.track(() {
try {
built = widget.builder(context);
} on Object catch (ex) {
error = ex;
}
});
if (!_reaction.hasObservables) {
widget.log(
'There are no observables detected in the builder function for ${_reaction.name}');
}
if (error != null) {
throw error;
}
return built;
}
@override
void dispose() {
_reaction.dispose();
super.dispose();
}
}
複製程式碼
猜猜我們看到了什麼, Observer繼承自StatefulWidget,看到這裡應該就豁然開朗了吧,其實就是在我們的widget上面套了一個父的widget,並且是StatefulWidget型別的,這樣一來,只要更新了父widget,同樣的我們的widget也就可以進行更新了。
在build的過程,可以看到呼叫了track方法,跟蹤原始碼可以發現就是先呼叫了傳入的方法(這裡對應的是我們widget的構建),然後就是把Observer插入觀察者佇列:
void _bindDependencies(Derivation derivation) {
final staleObservables =
derivation._observables.difference(derivation._newObservables);
final newObservables =
derivation._newObservables.difference(derivation._observables);
var lowestNewDerivationState = DerivationState.upToDate;
// Add newly found observables
for (final observable in newObservables) {
observable._addObserver(derivation);
// Computed = Observable + Derivation
if (observable is Computed) {
if (observable._dependenciesState.index >
lowestNewDerivationState.index) {
lowestNewDerivationState = observable._dependenciesState;
}
}
}
// Remove previous observables
for (final ob in staleObservables) {
ob._removeObserver(derivation);
}
if (lowestNewDerivationState != DerivationState.upToDate) {
derivation
.._dependenciesState = lowestNewDerivationState
.._onBecomeStale();
}
derivation
.._observables = derivation._newObservables
.._newObservables = {}; // No need for newObservables beyond this point
}
複製程式碼
接著我們需要找出觀察者的_onBecomeStale方法,如果跟蹤_onBecomeStale方法,可以發現最終呼叫的是reaction的run方法:
@override
void _run() {
if (_isDisposed) {
return;
}
_context.startBatch();
_isScheduled = false;
if (_context._shouldCompute(this)) {
try {
_onInvalidate();
} on Object catch (e) {
// Note: "on Object" accounts for both Error and Exception
_errorValue = MobXCaughtException(e);
_reportException(e);
}
}
_context.endBatch();
}
複製程式碼
其中的_onInvalidate()
就是在observer構成的時候傳入的方法:
void _invalidate() => setState(noOp);
static void noOp() {}
複製程式碼
看到這裡,其實已經水落石出了,就是通過呼叫的setState從而重新整理了widget。
總結
對於Mobx,本質就是在使用了被觀察資料的widget上面套了一個父的widget,而這個父的widget是一個StatefulWidget。 然後通過觀察者模式,發現資料更改時,通知觀察者,然後觀察者呼叫了setState了,更新了Observer,從而最後達到重新整理子widget的效果。
倉庫
點選flutter_demo,檢視完整程式碼。