Flutter mobx是一種狀態(tài)管理框架
核心概念
1. Observables
- 被觀察者衡未,數(shù)據(jù)的持有者尸执,即application的狀態(tài)持有者。創(chuàng)建 被觀察者樹缓醋,供UI或觀察者
Observer
消費(fèi)如失。2. Actions
- Action代表如何轉(zhuǎn)變Observables,即語義化的變異(例如對于
value
,不是直接value++
,而是包裝為increment()
)送粱。另Action保證變化完成后才通知Observer3. Reactions
使用
1.導(dǎo)入包
dependencies:
mobx: ^1.0.1
flutter_mobx: ^1.0.1
dev_dependencies:
mobx_codegen: ^1.0.1
build_runner: ^1.7.4
2.定義 Observable與Action
import 'package:mobx/mobx.dart';
part 'counter.g.dart';
// 運(yùn)行 flutter packages pub run build_runner build 生成
class Counter = CounterBase with _$Counter;
abstract class CounterBase with Store {
@observable
int value = 0;
@action
void increment() async {
value++;
print('$value');
}
}
3.觀察數(shù)據(jù)與發(fā)送Action
import 'package:flutter/material.dart';
import 'counter.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
class MobxTester extends StatelessWidget {
final Counter _counter=Counter();
@override
Widget build(BuildContext context) {
print('build');
return Scaffold(
appBar: AppBar(
title: Text('mobx demo'),
),
body: Center(
// mobx 觀察者 觀察數(shù)據(jù)
child: Observer(
builder: (_)=>Text(_counter.value.toString()),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
// 發(fā)送 action
_counter.increment();
},
),
);
}
}
4.VS Code 模板代碼
{
"Create Mobx Observales": {
"prefix": "mobx",
"body": [
"import 'package:mobx/mobx.dart';",
"http://*.g.dart will be created by cmd:",
"http://flutter packages pub run build_runner build",
"part '${TM_FILENAME_BASE}.g.dart';",
"class $1 = $1Base with _$$1;",
"abstract class $1Base with Store {",
" //TODO create observable",
" @observable",
" $2",
" //TODO create action method",
" @action",
" $3",
" //TODO create computed method",
" //@computed",
" $4",
"}"
],
"description": "Create Mobx Observales"
}
}