-
-
Notifications
You must be signed in to change notification settings - Fork 901
/
provider_base.dart
300 lines (261 loc) · 8.53 KB
/
provider_base.dart
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
part of '../framework.dart';
/// A callback used by providers to create the value exposed.
///
/// If an exception is thrown within that callback, all attempts at reading
/// the provider associated with the given callback will throw.
///
/// The parameter [ref] can be used to interact with other providers
/// and the life-cycles of this provider.
///
/// See also:
///
/// - [Ref], which exposes the methods to read other providers.
/// - [Provider], a provider that uses [Create] to expose an immutable value.
@internal
typedef Create<T, R extends Ref> = T Function(R ref);
/// A callback used to catches errors
@internal
typedef OnError = void Function(Object, StackTrace);
/// A base class for _all_ providers.
@immutable
abstract class ProviderBase<State> extends ProviderOrFamily
with ProviderListenable<State>
implements ProviderOverride, Refreshable<State> {
/// A base class for _all_ providers.
ProviderBase({
required this.name,
required this.from,
required this.argument,
required this.debugGetCreateSourceHash,
});
@override
ProviderBase get _origin => this;
@override
ProviderBase get _override => this;
/// A debug-only fucntion for obtaining a hash of the source code of the
/// initialization function.
///
/// If after a hot-reload this function returns a different result, the
/// provider will be re-executed.
///
/// This variable is only set by `riverpod_generator`.
final String Function()? debugGetCreateSourceHash;
/// {@template riverpod.name}
/// A custom label for providers.
///
/// This is picked-up by devtools and [toString] to show better messages.
/// {@endtemplate}
final String? name;
/// If this provider was created with the `.family` modifier, [from] is the `.family` instance.
@override
final Family? from;
/// If this provider was created with the `.family` modifier, [argument] is
/// the variable that was used.
final Object? argument;
@override
List<ProviderOrFamily>? get allTransitiveDependencies =>
dependencies == null ? null : _allTransitiveDependencies(dependencies!);
@override
ProviderSubscription<State> addListener(
Node node,
void Function(State? previous, State next) listener, {
required void Function(Object error, StackTrace stackTrace)? onError,
required void Function()? onDependencyMayHaveChanged,
required bool fireImmediately,
}) {
onError ??= Zone.current.handleUncaughtError;
final element = node.readProviderElement(this);
element.flush();
if (fireImmediately) {
handleFireImmediately(
element.getState()!,
listener: listener,
onError: onError,
);
}
element._onListen();
return node._listenElement(
element,
listener: listener,
onError: onError,
);
}
@override
State read(Node node) {
final element = node.readProviderElement(this);
element.flush();
// In case `read` was called on a provider that has no listener
element.mayNeedDispose();
return element.requireState;
}
/// An internal method that defines how a provider behaves.
@visibleForOverriding
ProviderElementBase<State> createElement();
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
int get hashCode {
if (from == null) return super.hashCode;
return from.hashCode ^ argument.hashCode;
}
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
if (from == null) return identical(other, this);
return other.runtimeType == runtimeType &&
other is ProviderBase<State> &&
other.from == from &&
other.argument == argument;
}
@override
String toString() {
var leading = '';
if (from != null) {
leading = '($argument)';
}
var trailing = '';
if (name != null) {
trailing = '$name:';
}
return '$trailing${describeIdentity(this)}$leading';
}
}
var _debugIsRunningSelector = false;
class _ExternalProviderSubscription<State>
implements ProviderSubscription<State> {
_ExternalProviderSubscription._(
this._listenedElement,
this._listener, {
required this.onError,
});
final void Function(State? previous, State next) _listener;
final ProviderElementBase<State> _listenedElement;
final void Function(Object error, StackTrace stackTrace) onError;
var _closed = false;
@override
void close() {
_closed = true;
_listenedElement._externalDependents.remove(this);
_listenedElement._onRemoveListener();
}
@override
State read() {
if (_closed) {
throw StateError(
'called ProviderSubscription.read on a subscription that was closed',
);
}
return _listenedElement.readSelf();
}
}
/// When a provider listens to another provider using `listen`
class _ProviderListener<State> implements ProviderSubscription<State> {
_ProviderListener._({
required this.listenedElement,
required this.dependentElement,
required this.listener,
required this.onError,
});
// TODO can't we type it properly?
final void Function(Object? prev, Object? state) listener;
final ProviderElementBase<Object?> dependentElement;
final ProviderElementBase<State> listenedElement;
final OnError onError;
@override
void close() {
dependentElement._listenedProviderSubscriptions.remove(this);
listenedElement
.._subscribers.remove(this)
.._onRemoveListener();
}
@override
State read() => listenedElement.readSelf();
}
/// A mixin to add [overrideWithValue] capability to a provider.
// TODO merge with Provider directy
mixin OverrideWithValueMixin<State> on ProviderBase<State> {
/// {@template riverpod.overrridewithvalue}
/// Overrides a provider with a value, ejecting the default behaviour.
///
/// This will also disable the auto-scoping mechanism, meaning that if the
/// overridden provider specified [dependencies], it will have no effect.
///
/// Some common use-cases are:
/// - testing, by replacing a service with a fake implementation, or to reach
/// a very specific state easily.
/// - multiple environments, by changing the implementation of a class
/// based on the platform or other parameters.
///
/// This function should be used in combination with `ProviderScope.overrides`
/// or `ProviderContainer.overrides`:
///
/// ```dart
/// final myService = Provider((ref) => MyService());
///
/// runApp(
/// ProviderScope(
/// overrides: [
/// myService.overrideWithValue(
/// // Replace the implementation of MyService with a fake implementation
/// MyFakeService(),
/// ),
/// ],
/// child: MyApp(),
/// ),
/// );
/// ```
/// {@endtemplate}
Override overrideWithValue(State value) {
return ProviderOverride(
origin: this,
override: ValueProvider<State>(value),
);
}
}
/// A mixin to add `overrideWithProvider` capability to providers.
extension OverrideWithProviderExtension<State,
ProviderType extends ProviderBase<State>> on ProviderType {
/// {@template riverpod.overridewithprovider}
/// Overrides a provider with a value, ejecting the default behaviour.
///
/// This will also disable the auto-scoping mechanism, meaning that if the
/// overridden provider specified `dependencies`, it will have no effect.
///
/// The override must not specify a `dependencies`.
///
/// Some common use-cases are:
/// - testing, by replacing a service with a fake implementation, or to reach
/// a very specific state easily.
/// - multiple environments, by changing the implementation of a class
/// based on the platform or other parameters.
///
/// This function should be used in combination with `ProviderScope.overrides`
/// or `ProviderContainer.overrides`:
///
/// ```dart
/// final myService = Provider((ref) => MyService());
///
/// runApp(
/// ProviderScope(
/// overrides: [
/// myService.overrideWithProvider(
/// // Replace the implementation of the provider with a different one
/// Provider((ref) {
/// ref.watch('other');
/// return MyFakeService(),
/// }),
/// ),
/// ],
/// child: MyApp(),
/// ),
/// );
/// ```
/// {@endtemplate}
@Deprecated('Will be removed in 3.0.0. Use overrideWith instead.')
Override overrideWithProvider(ProviderType override) {
assert(
override.dependencies == null,
'When using overrideWithProvider, the override cannot specify `dependencies`.',
);
return ProviderOverride(origin: this, override: override);
}
}