- MobX.dart网站上的 “ 入门指南”
- mobxjs
- video
- 组织Stores
安装依赖
dependencies:
mobx:
flutter_mobx:
dev_dependencies:
build_runner: ^1.3.1
mobx_codegen:
编写store
/// counter.dart
import 'package:mobx/mobx.dart';
// 包含生成的文件
part 'counter.g.dart';
class Counter = _Counter with _$Counter;
// The store-class
abstract class _Counter with Store {
/// 定义state
@observable
int value = 0;
/// 定义修改state的事件
/// MobX.dart自动处理异步操作,不需要使用runInAction包装代码
@action
void increment() {
value++;
}
/// 定义计算属性
@computed
String get valueString => 'value is $value';
}
build
flutter packages pub run build_runner build // 执行一次build命令
flutter packages pub run build_runner watch // 文件更改自动打包
flutter packages pub run build_runner watch --delete-conflicting-outputs // 删除旧文件在打包
UI
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'counter.dart'; // Import the Counter
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DashPage(),
);
}
}
class DashPage extends StatefulWidget {
@override
_DashPageState createState() => _DashPageState();
}
class _DashPageState extends State {
int _currentIndex = 0;
final PageController _controller = PageController();
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,
fixedColor: Colors.purple,
onTap: (int index) {
setState(() {
_currentIndex = index;
_controller.jumpToPage(index);
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
activeIcon: Icon(Icons.home),
title: Text("Home")),
BottomNavigationBarItem(
icon: Icon(Icons.search),
activeIcon: Icon(Icons.search),
title: Text("Search")),
],
),
body: PageView(
controller: _controller,
onPageChanged: (int index) {
setState(() {
_currentIndex = index;
});
},
children: [
HomePage(),
Center(child: Text('Search Page')),
],
),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State {
final counter = Counter();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('demo'),
),
body: Column(
children: [
Observer(builder: (_) => Text(counter.value.toString())),
Observer(builder: (_) => Text(counter.valueString)),
OutlineButton(
child: Text('add'),
onPressed: counter.increment,
),
],
),
);
}
}