5 Star 95 Fork 41

island-coder / FlutterBeginner

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
model_binding_v1.dart 1.89 KB
一键复制 编辑 原始数据 按行查看 历史
import 'package:flutter/material.dart';
class ModelBindingV1 extends StatefulWidget {
ModelBindingV1({Key key, this.initialModel = const ViewModel(), this.child})
: assert(initialModel != null),
super(key: key);
final ViewModel initialModel;
final Widget child;
@override
_ModelBindingV1State createState() => _ModelBindingV1State();
}
class _ModelBindingV1State extends State<ModelBindingV1> {
ViewModel currentModel = ViewModel();
void updateModel(ViewModel newModel) {
if (currentModel != newModel) {
setState(() {
currentModel = newModel;
});
}
}
@override
Widget build(BuildContext context) {
return _ModelBindingScope(
modelBindingState: this,
child: widget.child,
);
}
}
class ViewModel {
final int value;
const ViewModel({this.value = 0});
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other.runtimeType != runtimeType) {
return false;
}
final ViewModel otherModel = other;
return otherModel.value == value;
}
@override
int get hashCode => value.hashCode;
static ViewModel of(BuildContext context) {
_ModelBindingScope scope =
context.dependOnInheritedWidgetOfExactType(aspect: _ModelBindingScope);
return scope.modelBindingState.currentModel;
}
static void update(BuildContext context, ViewModel newModel) {
_ModelBindingScope scope =
context.dependOnInheritedWidgetOfExactType(aspect: _ModelBindingScope);
scope.modelBindingState.updateModel(newModel);
}
}
class _ModelBindingScope extends InheritedWidget {
_ModelBindingScope({
Key key,
@required this.modelBindingState,
Widget child,
}) : assert(modelBindingState != null),
super(key: key, child: child);
final _ModelBindingV1State modelBindingState;
@override
bool updateShouldNotify(_ModelBindingScope oldWidget) => true;
}
Dart
1
https://gitee.com/island-coder/flutter-beginner.git
git@gitee.com:island-coder/flutter-beginner.git
island-coder
flutter-beginner
FlutterBeginner
master

搜索帮助