Flutter UI与数据分离(Provider)
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
class Select extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return ChangeNotifierProvider.value(value: SelectModel(),child: SelectWidget(),);
}
}
// UI层
class SelectWidget extends StatefulWidget{
@override
_SelectWidget createState() {
return _SelectWidget();
}
}
class _SelectWidget extends State<SelectWidget>{
SelectModel selectModel;
@override
void initState() {
// TODO: implement initState
super.initState();
WidgetsBinding.instance.addPostFrameCallback((callback){
selectModel = Provider.of<SelectModel>(context);
});
}
@override
Widget build(BuildContext context) {
return Consumer<SelectModel>(builder: (BuildContext context,SelectModel _selectModel,child){
return Text('${_selectModel.count}');
},);
}
}
// 逻辑层
class SelectModel with ChangeNotifier{
int _a = 0;
int get count => _a;
increment(){
Future.delayed(Duration(seconds: 3)).then((res){
_a = _a+1;
notifyListeners();
});
}
}
本文标题:Flutter UI与数据分离(Provider)
本文链接:https://www.haomeiwen.com/subject/ophubctx.html
网友评论