关于provider 网上有很多讲解,这里就不过多做赘述了,对其原理不懂的可以去flutter官网里的flutter实战书里详细学习,这里就provider的使用做了封装,简单易用,我也是参考了下博客里的坑友们的知识😁😁,话不多说上干货
首先封一个 BaseModel extends ChangeNotifier,
然后做一个状态枚举,用来做网络请求的先加载动画到数据展示用
enum ViewState { Loading, Success, Failure, None }
在对BaseWidget<T extends ChangeNotifier> extends StatefulWidget
至此 公共 base_widget.dart 封装完毕,接下来就是 viewmodel 和 providerservice的写法和具体使用了,咱们继续直接上代码
base_widget.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
enum ViewState { Loading, Success, Failure, None }
class BaseModel extends ChangeNotifier {
ViewState _state = ViewState.None;
ViewState get state => _state;
void setState(ViewState viewState) {
_state = viewState;
notifyListeners();
}
}
class BaseWidget<T extends ChangeNotifier> extends StatefulWidget {
final Widget Function(BuildContext context, T model, Widget child) builder;
final T model;
final Widget child;
final Function(T) onModelReady;
BaseWidget({
Key key,
this.builder,
this.model,
this.child,
this.onModelReady,
}) : super(key: key);
_BaseWidgetState<T> createState() => _BaseWidgetState<T>();
}
class _BaseWidgetState<T extends ChangeNotifier> extends State<BaseWidget<T>> {
T model;
@override
void initState() {
model = widget.model;
if (widget.onModelReady != null) {
widget.onModelReady(model);
}
super.initState();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<T>(
create: (BuildContext context) => model,
child: Consumer<T>(
builder: widget.builder,
child: widget.child,
),
);
}
}
viewmodel
/// viewModel
class SpareDetailModel extends BaseModel {
SpareDetailServive _detailServive;
String info = '请登录';
bool show = false;
SpareDetailModel({@required SpareDetailServive detailServive})
: _detailServive = detailServive;
// ignore: missing_return
Future<String> login(String pwd) async {
setState(ViewState.Loading);
info = await _detailServive.login(pwd);
setState(ViewState.Success);
}
// ignore: missing_return
Future<bool> rowShow(int index) async {
if (index == 0) {
show = true;
} else {
show = false;
}
setState(ViewState.Success);
}
}
provider_service
/// api
class SpareDetailServive {
static const String Login_path = 'xxxxxx';
Future<String> login(String pwd) async {
return new Future.delayed(const Duration(seconds: 1), () => "登录成功");
}
}
具体使用方式
BaseWidget<SpareDetailModel>(
model: SpareDetailModel(detailServive: SpareDetailServive()),
builder: (context, model, child) => GestureDetector(
onTap: () { model.login(pwd),print('model.info') })
以上就是 provider的封装后的基本使用方法,可用_pageThree() {return container(); }这种方式定义多个widget也就能分别对不同的widget做provider做管理,机智的一批,后续会附上demo,以供参考,百嫖欢乐,点个赞,以后更新更多百嫖福利