flutter 通过scopedmodel来传递状态:
0 先要添加必要的plugin:
scoped_model: ^0.3.0
1 创建数据类:
class Mycount{
int count;
Mycount(this.count);
void addcount(){
count = count+1;
}
}
2 创建model类:
class Countmodel extends Model{
Mycount count = new Mycount(0);
int get counts=>count.count;
void add(){
count.addcount();
notifyListeners();
}
}
3 将数据通过scopedmodel的方式传递:
class Inheritedwidget extends StatefulWidget {
@override
_InheritedWidgetState createState() => _InheritedWidgetState();
}
class _InheritedWidgetState extends State<Inheritedwidget> {
int count=0;
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
print(count);
return ScopedModel(
model:Countmodel(),
child:Scaffold(
backgroundColor: Colors.blue,
appBar: AppBar(title: Text("inherited widget"),),body: Container(
child: Center(
child: Column(
children: <Widget>[
Text("class0"),
class1(),
],
),
),
),
floatingActionButton: ScopedModelDescendant<Countmodel>(
builder: (context,_,model){
return FloatingActionButton(onPressed: (){
return model.add();
},child: Text("add"),);
},
),
),
);
}
}