cat

dabaicai has a cat

0%

provider源码

![image-20240629上午104037786](/Users/laiyuling/Library/Application Support/typora-user-images/image-20240629上午104037786.png)

  • 1处代码
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class ChangeNotifierProvider<T extends ChangeNotifier?>
extends ListenableProvider<T> {
/// Creates a [ChangeNotifier] using `create` and automatically
/// disposes it when [ChangeNotifierProvider] is removed from the widget tree.
///
/// `create` must not be `null`.
ChangeNotifierProvider({
Key? key,
required Create<T> create,
bool? lazy,
TransitionBuilder? builder,
Widget? child,
}) : super(
key: key,
create: create,
dispose: _dispose,
lazy: lazy,
builder: builder,
child: child,
);



class ListenableProvider<T extends Listenable?> extends InheritedProvider<T> {
/// Creates a [Listenable] using [create] and subscribes to it.
///
/// [dispose] can optionally passed to free resources
/// when [ListenableProvider] is removed from the tree.
///
/// [create] must not be `null`.
ListenableProvider({
Key? key,
required Create<T> create,
Dispose<T>? dispose,
bool? lazy,
TransitionBuilder? builder,
Widget? child,
}) : super(
key: key,
startListening: _startListening,
create: create,
dispose: dispose,
lazy: lazy,
builder: builder,
child: child,
);


class InheritedProvider<T> extends SingleChildStatelessWidget {
/// Creates a value, then expose it to its descendants.
///
/// The value will be disposed of when [InheritedProvider] is removed from
/// the widget tree.
InheritedProvider({
Key? key,
Create<T>? create,
T Function(BuildContext context, T? value)? update,
UpdateShouldNotify<T>? updateShouldNotify,
void Function(T value)? debugCheckInvalidValueType,
StartListening<T>? startListening,
Dispose<T>? dispose,
this.builder,
bool? lazy,
Widget? child,
}) : _lazy = lazy,
_delegate = _CreateInheritedProvider(
create: create,
update: update,
updateShouldNotify: updateShouldNotify,
debugCheckInvalidValueType: debugCheckInvalidValueType,
startListening: startListening,
dispose: dispose,
),
super(key: key, child: child);


@override
_InheritedProviderElement<T> createElement() {
return _InheritedProviderElement<T>(this);
}

@override
Widget buildWithChild(BuildContext context, Widget? child) {
return _InheritedProviderScope<T?>(
owner: this,
// ignore: no_runtimetype_tostring
debugType: kDebugMode ? '$runtimeType' : '',
child: builder != null
? Builder(
builder: (context) => builder!(context, child),
)
: child!,
);
}

ChangeNotifierProvider一路找夫类的构造函数到 InheritedProvider,此时创建了 _delegate = _CreateInheritedProvider并将 create 属性赋值,即等于 ChangeNotifierProvider 的 create 方法

1
2
3
4
5
6
ChangeNotifierProvider(
create: (context) =>
DateTimeSettingModel(mContext: context, params: params),
child: DateTimeSettingPageWidget(),
);

_CreateInheritedProvider 类中有一个 createState 方法,返回 _CreateInheritedProviderState 对象(下面要用到,有印象即可)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class _CreateInheritedProvider<T> extends _Delegate<T> {
_CreateInheritedProvider({
this.create,
this.update,
UpdateShouldNotify<T>? updateShouldNotify,
this.debugCheckInvalidValueType,
this.startListening,
this.dispose,
}) : assert(create != null || update != null),
_updateShouldNotify = updateShouldNotify;

final Create<T>? create;
final T Function(BuildContext context, T? value)? update;
final UpdateShouldNotify<T>? _updateShouldNotify;
final void Function(T value)? debugCheckInvalidValueType;
final StartListening<T>? startListening;
final Dispose<T>? dispose;

@override
_CreateInheritedProviderState<T> createState() =>
_CreateInheritedProviderState();
}
  • 2处代码分析
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
context.read<DateTimeSettingModel>();

// provider 拓展方法
extension ReadContext on BuildContext {
T read<T>() {
return Provider.of<T>(this, listen: false);
}
}

static T of<T>(BuildContext context, {bool listen = true}) {
......
final inheritedElement = _inheritedElementOf<T>(context); // 2.1处
final value = inheritedElement?.value; // 2.2处

if (_isSoundMode) {
if (value is! T) {
throw ProviderNullException(T, context.widget.runtimeType);
}
return value;
}

return value as T;
}


// 2.1处
static _InheritedProviderScopeElement<T?>? _inheritedElementOf<T>(
BuildContext context,
) {
......
_InheritedProviderScopeElement<T?>? inheritedElement;
// if这里不会进去,因为 widget 是StatelessWidget
if (context.widget is _InheritedProviderScope<T?>) {
// An InheritedProvider<T>'s update tries to obtain a parent provider of
// the same type.
context.visitAncestorElements((parent) {
inheritedElement = parent.getElementForInheritedWidgetOfExactType<
_InheritedProviderScope<T?>>()
as _InheritedProviderScopeElement<T?>?;
return false;
});
} else {
inheritedElement = context.getElementForInheritedWidgetOfExactType<
_InheritedProviderScope<T?>>() as _InheritedProviderScopeElement<T?>?;
}

if (inheritedElement == null && null is! T) {
throw ProviderNotFoundException(T, context.widget.runtimeType);
}

return inheritedElement;
}

// 来到flutter的framework,这里返回了 context 类型的 InheritedElement,context 类型在上面的就是 InheritedProvider buildWithChild 方法返回 _InheritedProviderScope 的 _InheritedProviderScopeElement 类型(createElement 方法创建的)
@override
InheritedElement? getElementForInheritedWidgetOfExactType<T extends InheritedWidget>() {
assert(_debugCheckStateIsActiveForAncestorLookup());
final InheritedElement? ancestor = _inheritedWidgets == null ? null : _inheritedWidgets![T];
return ancestor;
}

// _inheritedWidgets的来源
void _updateInheritance() {
assert(_lifecycleState == _ElementLifecycle.active);
_inheritedWidgets = _parent?._inheritedWidgets;
}
// 元素挂载的时候调用 _updateInheritance,将父节点的_inheritedWidgets一层一层传递给子节点,要是本节点也是InheritedElement类型的,将本节点也加入到 _inheritedWidgets 容器里面去
@mustCallSuper
void mount(Element? parent, Object? newSlot) {
......
final Key? key = widget.key;
if (key is GlobalKey) {
owner!._registerGlobalKey(key, this);
}
_updateInheritance();
attachNotificationTree();
}

//看一眼容器类型,key是运行时类型,value是元素本身
Map<Type, InheritedElement>? _inheritedWidgets;
@override
// 加入容器的方法
void _updateInheritance() {
assert(_lifecycleState == _ElementLifecycle.active);
final Map<Type, InheritedElement>? incomingWidgets = _parent?._inheritedWidgets;
if (incomingWidgets != null) {
_inheritedWidgets = HashMap<Type, InheritedElement>.of(incomingWidgets);
} else {
_inheritedWidgets = HashMap<Type, InheritedElement>();
}
_inheritedWidgets![widget.runtimeType] = this;
}


// 2.2处 此时知道了inheritedElement是_InheritedProviderScopeElement
final value = inheritedElement?.value;

// _delegateState = _CreateInheritedProviderState
@override
T get value => _delegateState.value;

// widget 是 InheritedProvider buildWithChild 方法返回的 _InheritedProviderScope
// owner 是 InheritedProvider
// _delegate 是上面有印象的 _CreateInheritedProvider 对象
// createState 返回 _CreateInheritedProviderState
@override
void performRebuild() {
if (_firstBuild) {
_firstBuild = false;
_delegateState = widget.owner._delegate.createState()..element = this;
}
super.performRebuild();
}
class _InheritedProviderScope<T> extends InheritedWidget {
const _InheritedProviderScope({
required this.owner,//InheritedProvider
required this.debugType,
required Widget child,
}) : assert(null is T),
super(child: child);

final InheritedProvider<T> owner;
}



class _CreateInheritedProviderState
@override
T get value {
if (_didInitValue && !_didSucceedInit) {
throw StateError(
'Tried to read a provider that threw during the creation of its value.\n'
'The exception occurred during the creation of type $T.',
);
}
bool? _debugPreviousIsInInheritedProviderCreate;
bool? _debugPreviousIsInInheritedProviderUpdate;

assert(() {
_debugPreviousIsInInheritedProviderCreate =
debugIsInInheritedProviderCreate;
_debugPreviousIsInInheritedProviderUpdate =
debugIsInInheritedProviderUpdate;
return true;
}());

if (!_didInitValue) {
_didInitValue = true;
if (delegate.create != null) {
assert(debugSetInheritedLock(true));
try {
assert(() {
debugIsInInheritedProviderCreate = true;
debugIsInInheritedProviderUpdate = false;
return true;
}());
// 调用的即是 create: (context) =>
// DateTimeSettingModel(mContext: context, params: params),
_value = delegate.create!(element!);
_didSucceedInit = true;
} finally {
assert(() {
debugIsInInheritedProviderCreate =
_debugPreviousIsInInheritedProviderCreate!;
debugIsInInheritedProviderUpdate =
_debugPreviousIsInInheritedProviderUpdate!;
return true;
}());
}
assert(debugSetInheritedLock(false));

assert(() {
delegate.debugCheckInvalidValueType?.call(_value as T);
return true;
}());
}
if (delegate.update != null) {
try {
assert(() {
debugIsInInheritedProviderCreate = false;
debugIsInInheritedProviderUpdate = true;
return true;
}());
_value = delegate.update!(element!, _value);
_didSucceedInit = true;
} finally {
assert(() {
debugIsInInheritedProviderCreate =
_debugPreviousIsInInheritedProviderCreate!;
debugIsInInheritedProviderUpdate =
_debugPreviousIsInInheritedProviderUpdate!;
return true;
}());
}

assert(() {
delegate.debugCheckInvalidValueType?.call(_value as T);
return true;
}());
}
_didSucceedInit = true;
}

element!._isNotifyDependentsEnabled = false;
_removeListener ??= delegate.startListening?.call(element!, _value as T);
element!._isNotifyDependentsEnabled = true;
assert(delegate.startListening == null || _removeListener != null);
return _value as T;
}

总结:在最初的时候并没有去构建DateTimeSettingModel对象,而是等到用到的时候再去真正的构建对象,context.read<>或者 context.watch<>