美文网首页
Flutter UI与数据分离(Provider)

Flutter UI与数据分离(Provider)

作者: 有一种感动叫做丶只有你懂 | 来源:发表于2019-11-19 17:45 被阅读0次
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