Flutter State-01

Jared Yuan Lv2

自定义 Provider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class CustomProvider<T extends Listenable> extends StatefulWidget {
final T Function() create;
final Widget child;
const CustomProvider({Key? key, required this.child, required this.create}) : super(key: key);

@override
State<CustomProvider> createState() => _CustomState<T>();

static T of<T>(BuildContext context,{bool listen = true}) {
if(listen) {
return context.dependOnInheritedWidgetOfExactType<CustomInheritedWidget<T>>()!.model;
} else {
return (context.getElementForInheritedWidgetOfExactType<CustomInheritedWidget<T>>()!.widget as CustomInheritedWidget).model;
}

}
}

class _CustomState<T extends Listenable> extends State<CustomProvider<T>> {

late T model;

@override
void initState() {
// TODO: implement initState
super.initState();
model = widget.create();
}

@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: model,
builder: (BuildContext context, Widget? child) {
return CustomInheritedWidget(model: model,
child: widget.child);
},
);
}
}


class CustomInheritedWidget<T> extends InheritedWidget {
final T model;

const CustomInheritedWidget({super.key, required this.model,required super.child});

static CustomInheritedWidget of<T>(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<CustomInheritedWidget<T>>()!;
}

@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) {
print("update");
return true;
}
}

/// extension如果没有取名字只能在本文件中使用,属于私有扩展。起名字可以供其他外部使用
extension Consumer on BuildContext {
T watch<T>() => CustomProvider.of(this);
T read<T>() => CustomProvider.of(this,listen: false);
}
  • Title: Flutter State-01
  • Author: Jared Yuan
  • Created at : 2023-09-13 21:23:58
  • Updated at : 2023-10-21 20:35:27
  • Link: https://redefine.ohevan.com/2023/09/13/Flutter/Flutter_state_01/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
Flutter State-01