Flutter mobx是一种状态管理框架
核心概念
1. Observables
- 被观察者,数据的持有者,即application的状态持有者。创建 被观察者树,供UI或观察者
Observer
消费。2. Actions
- Action代表如何转变Observables,即语义化的变异(例如对于
value
,不是直接value++
,而是包装为increment()
)。另Action保证变化完成后才通知Observer3. Reactions
使用
1.导入包
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';
// 运行 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.观察数据与发送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 观察者 观察数据
child: Observer(
builder: (_)=>Text(_counter.value.toString()),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
// 发送 action
_counter.increment();
},
),
);
}
}
4.VS Code 模板代码
{
"Create Mobx Observales": {
"prefix": "mobx",
"body": [
"import 'package:mobx/mobx.dart';",
"//*.g.dart will be created by cmd:",
"//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"
}
}