關(guān)于provider 網(wǎng)上有很多講解,這里就不過多做贅述了徊件,對其原理不懂的可以去flutter官網(wǎng)里的flutter實戰(zhàn)書里詳細(xì)學(xué)習(xí)奸攻,這里就provider的使用做了封裝蒜危,簡單易用,我也是參考了下博客里的坑友們的知識????睹耐,話不多說上干貨
首先封一個 BaseModel extends ChangeNotifier,
然后做一個狀態(tài)枚舉辐赞,用來做網(wǎng)絡(luò)請求的先加載動畫到數(shù)據(jù)展示用
enum ViewState { Loading, Success, Failure, None }
在對BaseWidget<T extends ChangeNotifier> extends StatefulWidget
至此 公共 base_widget.dart 封裝完畢,接下來就是 viewmodel 和 providerservice的寫法和具體使用了硝训,咱們繼續(xù)直接上代碼
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做管理,機(jī)智的一批窖梁,后續(xù)會附上demo赘风,以供參考,百嫖歡樂纵刘,點個贊邀窃,以后更新更多百嫖福利