前言
封装的目的,在于减少项目对第三方库的依赖,如果项目要更改第三方框架,如果项目对第三方库依赖较深,改起来就很麻烦,因此,这里我们对provider进行一次简单的二次封装。
ChangeNotifyProvider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class ProviderWidget<T extends ChangeNotifier> extends StatefulWidget {
T viewmodel;
Widget child;
Function(BuildContext, T, Widget) builder;
Function(T model) load;
ProviderWidget(
{@required this.viewmodel,
this.child,
@required this.builder,
this.load,
Key key})
: super(key: key);
@override
_ProviderWidgetState createState() => _ProviderWidgetState<T>();
}
class _ProviderWidgetState<T extends ChangeNotifier>
extends State<ProviderWidget<T>> {
@override
void initState() {
super.initState();
// 控件初始化
if (widget.load != null) {
widget.load(widget.viewmodel);
}
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => widget.viewmodel,
child: Consumer<T>(
builder: (context, value, child) =>
widget.builder(context, value, child),
child: widget.child,
));
}
}
ChangeNotifier
import 'package:flutter/material.dart';
class BaseViewModel extends ChangeNotifier {
void notify() {
notifyListeners();
}
}
使用
首先建立一个BaseViewModel类
import 'package:providerStudy/viewmodel/base/BaseViewModel.dart';
class HomePageViewModel extends BaseViewModel {
String text = "初始";
void touch() {
this.text = "被点击";
print(this.text);
notify();
}
}
然后再页面中进行使用