scoped_model
文章目录
scoped_model is a third-part Flutter Package,allow you to easily pass a data Model from a parent Widget down to it’s descendants.
Usage
首先创建一个继承Model的类,这个类的作用是保持Widget的state,修改数据后调用notifyListeners;
1
2
3
4
5
6
7
8
9
10
11import 'package:scoped_model/scoped_model.dart';
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
/// First, increment the counter/
_counter++;
/// Then notify all the listeners./
notifyListeners();
}
}ScopedModel是一个带model和child参数的Widget,用于初始化并传递创建好的Model类,包裹于其中的页面StatelessWidget相当于Listeners;
1
2
3
4
5
6
7
8
9
10
11
12
13
14class MyApp extends StatelessWidget {
final CounterModel model;
const MyApp({Key key,@required this.model}):super(key:key);
@override
Widget build(BuildContext context) {
return ScopedModel(
model: model,
child: MaterialApp(
title: 'scoped model demo',
home: CountPage(),
),
);
}
}包裹于ScopedModelDescendant的Widget用于操作Model的数据(增删改查);另外一种获取方式是在重写build函数中通过
final username = ScopedModel.of<UserModel>(context,rebuildOnChange: true).username;
获取数据1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:flutter_temperate/models/counter_model.dart';
import 'package:flutter_temperate/ui/result_page.dart';
class CountPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('scoped model'),
backgroundColor: Colors.purple,
actions: <Widget>[
IconButton(tooltip: 'to result',icon: Icon(Icons.rotate_right),onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context) => ResultPage()));
},)
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('touch'),
ScopedModelDescendant<CounterModel>(
builder: (context,child,model){
return Text('${model.counter.toString()} times',style: TextStyle(
color: Colors.red,fontSize: 33.0,
),);
},
),
],
),
),
floatingActionButton: ScopedModelDescendant<CounterModel>(
builder: (context,child,model){
return FloatingActionButton(
onPressed: model.increment,
tooltip: 'add',
child: Icon(Icons.add),
);
},
),
);
}
}
Flutter状态管理的方式有很多,StatelessWidget(原生)、bloc、redux、rxdart,各有优劣,但是选择适合自己的很重要。thanks for your reading~