-
-
Notifications
You must be signed in to change notification settings - Fork 908
/
consumer.dart
661 lines (616 loc) · 21 KB
/
consumer.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import 'package:flutter/widgets.dart';
import 'package:meta/meta.dart';
import 'internals.dart';
/// An object that allows widgets to interact with providers.
abstract class WidgetRef {
/// The [BuildContext] of the widget associated to this [WidgetRef].
///
/// This is strictly identical to the [BuildContext] passed to [ConsumerWidget.build].
BuildContext get context;
/// Returns the value exposed by a provider and rebuild the widget when that
/// value changes.
///
/// See also:
///
/// - [ProviderListenable.select], which allows a widget to filter rebuilds by
/// observing only the selected properties.
/// - [listen], to react to changes on a provider, such as for showing modals.
T watch<T>(ProviderListenable<T> provider);
/// Determines whether a provider is initialized or not.
///
/// Writing logic that conditionally depends on the existence of a provider
/// is generally unsafe and should be avoided.
/// The problem is that once the provider gets initialized, logic that
/// depends on the existence or not of a provider won't be rerun; possibly
/// causing your state to get out of date.
///
/// But it can be useful in some cases, such as to avoid re-fetching an
/// object if a different network request already obtained it:
///
/// ```dart
/// final fetchItemList = FutureProvider<List<Item>>(...);
///
/// final fetchItem = FutureProvider.autoDispose.family<Item, String>((ref, id) async {
/// if (ref.exists(fetchItemList)) {
/// // If `fetchItemList` is initialized, we look into its state
/// // and return the already obtained item.
/// final itemFromItemList = ref.watch(
/// fetchItemList.selectAsync((items) => items.firstWhereOrNull((item) => item.id == id)),
/// );
/// if (itemFromItemList != null) return itemFromItemList;
/// }
///
/// // If `fetchItemList` is not initialized, perform a network request for
/// // "id" separately
///
/// final json = await http.get('api/items/$id');
/// return Item.fromJson(json);
/// });
/// ```
bool exists(ProviderBase<Object?> provider);
/// Listen to a provider and call `listener` whenever its value changes,
/// without having to take care of removing the listener.
///
/// The [listen] method should exclusively be used within the `build` method
/// of a widget:
///
/// ```dart
/// Consumer(
/// builder: (context, ref, child) {
/// ref.listen<int>(counterProvider, (prev, next) {
/// print('counter changed $next');
/// });
/// },
/// )
/// ```
///
/// When used inside `build`, listeners will automatically be removed
/// if a widget rebuilds and stops listening to a provider.
///
/// For listening to a provider from outside `build`, consider using [listenManual] instead.
///
/// This is useful for showing modals or other imperative logic.
void listen<T>(
ProviderListenable<T> provider,
void Function(T? previous, T next) listener, {
void Function(Object error, StackTrace stackTrace)? onError,
});
/// Listen to a provider and call `listener` whenever its value changes.
///
/// As opposed to [listen], [listenManual] is not safe to use within the `build`
/// method of a widget.
/// Instead, [listenManual] is designed to be used inside [State.initState] or
/// other [State] lifecycles.
///
/// [listenManual] returns a [ProviderSubscription] which can be used to stop
/// listening to the provider, or to read the current value exposed by
/// the provider.
///
/// It is not necessary to call [ProviderSubscription.close] inside [State.dispose].
/// When the widget that calls [listenManual] is disposed, the subscription
/// will be disposed automatically.
ProviderSubscription<T> listenManual<T>(
ProviderListenable<T> provider,
void Function(T? previous, T next) listener, {
void Function(Object error, StackTrace stackTrace)? onError,
bool fireImmediately,
});
/// Reads a provider without listening to it.
///
/// **AVOID** calling [read] inside build if the value is used only for events:
///
/// ```dart
/// Widget build(BuildContext context) {
/// // counter is used only for the onPressed of RaisedButton
/// final counter = ref.read(counterProvider);
///
/// return RaisedButton(
/// onPressed: () => counter.increment(),
/// );
/// }
/// ```
///
/// While this code is not bugged in itself, this is an anti-pattern.
/// It could easily lead to bugs in the future after refactoring the widget
/// to use `counter` for other things, but forget to change [read] into [Consumer]/`ref.watch(`.
///
/// **CONSIDER** calling [read] inside event handlers:
///
/// ```dart
/// Widget build(BuildContext context) {
/// return RaisedButton(
/// onPressed: () {
/// // as performant as the previous solution, but resilient to refactoring
/// ref.read(counterProvider).increment(),
/// },
/// );
/// }
/// ```
///
/// This has the same efficiency as the previous anti-pattern, but does not
/// suffer from the drawback of being brittle.
///
/// **AVOID** using [read] for creating widgets with a value that never changes
///
/// ```dart
/// Widget build(BuildContext context) {
/// // using read because we only use a value that never changes.
/// final model = ref.read(modelProvider);
///
/// return Text('${model.valueThatNeverChanges}');
/// }
/// ```
///
/// While the idea of not rebuilding the widget if unnecessary is good,
/// this should not be done with [read].
/// Relying on [read] for optimisations is very brittle and dependent
/// on an implementation detail.
///
/// **CONSIDER** using [Provider] or `select` for filtering unwanted rebuilds:
///
/// ```dart
/// Widget build(BuildContext context) {
/// // Using select to listen only to the value that used
/// final valueThatNeverChanges = ref.watch(modelProvider.select((model) {
/// return model.valueThatNeverChanges;
/// }));
///
/// return Text('$valueThatNeverChanges');
/// }
/// ```
///
/// While more verbose than [read], using [Provider]/`select` is a lot safer.
/// It does not rely on implementation details on `Model`, and it makes
/// impossible to have a bug where our UI does not refresh.
T read<T>(ProviderListenable<T> provider);
/// Forces a provider to re-evaluate its state immediately, and return the created value.
///
/// Writing:
///
/// ```dart
/// final newValue = ref.refresh(provider);
/// ```
///
/// is strictly identical to doing:
///
/// ```dart
/// ref.invalidate(provider);
/// final newValue = ref.read(provider);
/// ```
///
/// If you do not care about the return value of [refresh], use [invalidate] instead.
/// Doing so has the benefit of:
/// - making the invalidation logic more resilient by avoiding multiple
/// refreshes at once.
/// - possibly avoids recomputing a provider if it isn't
/// needed immediately.
///
/// This method is useful for features like "pull to refresh" or "retry on error",
/// to restart a specific provider.
///
/// For example, a pull-to-refresh may be implemented by combining
/// [FutureProvider] and a `RefreshIndicator`:
///
/// ```dart
/// final productsProvider = FutureProvider((ref) async {
/// final response = await httpClient.get('https://host.com/products');
/// return Products.fromJson(response.data);
/// });
///
/// class Example extends ConsumerWidget {
/// @override
/// Widget build(BuildContext context, WidgetRef ref) {
/// final Products products = ref.watch(productsProvider);
///
/// return RefreshIndicator(
/// onRefresh: () => ref.refresh(productsProvider.future),
/// child: ListView(
/// children: [
/// for (final product in products.items) ProductItem(product: product),
/// ],
/// ),
/// );
/// }
/// }
/// ```
@useResult
State refresh<State>(Refreshable<State> provider);
/// Invalidates the state of the provider, causing it to refresh.
///
/// As opposed to [refresh], the refresh is not immediate and is instead
/// delayed to the next read or next frame.
///
/// Calling [invalidate] multiple times will refresh the provider only
/// once.
///
/// Calling [invalidate] will cause the provider to be disposed immediately.
void invalidate(ProviderOrFamily provider);
}
/// A function that can also listen to providers
///
/// See also [Consumer]
typedef ConsumerBuilder = Widget Function(
BuildContext context,
WidgetRef ref,
Widget? child,
);
/// {@template riverpod.consumer}
/// Build a widget tree while listening to providers.
///
/// [Consumer] can be used to listen to providers inside a [StatefulWidget]
/// or to rebuild as few widgets as possible when a provider updates.
///
/// As an example, consider:
///
/// ```dart
/// final helloWorldProvider = Provider((_) => 'Hello world');
/// ```
///
/// We can then use [Consumer] to listen to `helloWorldProvider` inside a
/// [StatefulWidget] like so:
///
/// ```dart
/// class Example extends StatefulWidget {
/// @override
/// _ExampleState createState() => _ExampleState();
/// }
///
/// class _ExampleState extends State<Example> {
/// @override
/// Widget build(BuildContext context) {
/// return Consumer(
/// builder: (context, ref, child) {
/// final value = ref.watch(helloWorldProvider);
/// return Text(value); // Hello world
/// },
/// );
/// }
/// }
/// ```
///
/// **Note**
/// You can watch as many providers inside [Consumer] as you want to:
///
/// ```dart
/// Consumer(
/// builder: (context, ref, child) {
/// final value = ref.watch(someProvider);
/// final another = ref.watch(anotherProvider);
/// ...
/// },
/// );
/// ```
///
/// ## Performance optimizations
///
/// If your `builder` function contains a subtree that does not depend on the
/// animation, it is more efficient to build that subtree once instead of
/// rebuilding it on every provider update.
///
/// If you pass the pre-built subtree as the `child` parameter, the
/// Consumer will pass it back to your builder function so that you
/// can incorporate it into your build.
///
/// Using this pre-built child is entirely optional, but can improve
/// performance significantly in some cases and is therefore a good practice.
///
/// This sample shows how you could use a [Consumer]
///
/// ```dart
/// final counterProvider = StateProvider((ref) => 0);
///
/// class MyHomePage extends StatelessWidget {
/// MyHomePage({Key? key, required this.title}) : super(key: key);
/// final String title;
///
/// @override
/// Widget build(BuildContext context) {
/// return Scaffold(
/// appBar: AppBar(
/// title: Text(title)
/// ),
/// body: Center(
/// child: Column(
/// mainAxisAlignment: MainAxisAlignment.center,
/// children: <Widget>[
/// Text('You have pushed the button this many times:'),
/// Consumer(
/// builder: (BuildContext context, WidgetRef ref, Widget? child) {
/// // This builder will only get called when the counterProvider
/// // is updated.
/// final count = ref.watch(counterProvider);
///
/// return Row(
/// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
/// children: <Widget>[
/// Text('$count'),
/// child!,
/// ],
/// );
/// },
/// // The child parameter is most helpful if the child is
/// // expensive to build and does not depend on the value from
/// // the notifier.
/// child: Text('Good job!'),
/// )
/// ],
/// ),
/// ),
/// floatingActionButton: FloatingActionButton(
/// child: Icon(Icons.plus_one),
/// onPressed: () => ref.read(counterProvider.notifier).state++,
/// ),
/// );
/// }
/// }
/// ```
///
/// See also:
///
/// * [ConsumerWidget], a base-class for widgets that wants to listen to providers.
/// {@endtemplate}
@sealed
class Consumer extends ConsumerWidget {
/// {@template riverpod.consumer}
const Consumer({super.key, required ConsumerBuilder builder, Widget? child})
: _child = child,
_builder = builder;
final ConsumerBuilder _builder;
final Widget? _child;
@override
Widget build(BuildContext context, WidgetRef ref) {
return _builder(context, ref, _child);
}
}
/// {@template riverpod.consumerwidget}
/// A [StatelessWidget] that can listen to providers.
///
/// Using [ConsumerWidget], this allows the widget tree to listen to changes on
/// provider, so that the UI automatically updates when needed.
///
/// Do not modify any state or start any http request inside [build].
///
/// As a usage example, consider:
///
/// ```dart
/// final helloWorldProvider = Provider((_) => 'Hello world');
/// ```
///
/// We can then subclass [ConsumerWidget] to listen to `helloWorldProvider` like so:
///
/// ```dart
/// class Example extends ConsumerWidget {
/// const Example({Key? key}): super(key: key);
///
/// @override
/// Widget build(BuildContext context, WidgetRef ref) {
/// final value = ref.watch(helloWorldProvider);
/// return Text(value); // Hello world
/// }
/// }
/// ```
///
/// **Note**
/// You can watch as many providers inside [build] as you want to:
///
/// ```dart
/// @override
/// Widget build(BuildContext context, WidgetRef ref) {
/// final value = ref.watch(someProvider);
/// final another = ref.watch(anotherProvider);
/// return Text(value); // Hello world
/// }
/// ```
///
/// For reading providers inside a [StatefulWidget] or for performance
/// optimizations, see [Consumer].
/// {@endtemplate}
abstract class ConsumerWidget extends ConsumerStatefulWidget {
/// {@macro riverpod.consumerwidget}
const ConsumerWidget({super.key});
/// Describes the part of the user interface represented by this widget.
///
/// The framework calls this method when this widget is inserted into the tree
/// in a given [BuildContext] and when the dependencies of this widget change
/// (e.g., an [InheritedWidget] referenced by this widget changes). This
/// method can potentially be called in every frame and should not have any side
/// effects beyond building a widget.
///
/// The framework replaces the subtree below this widget with the widget
/// returned by this method, either by updating the existing subtree or by
/// removing the subtree and inflating a new subtree, depending on whether the
/// widget returned by this method can update the root of the existing
/// subtree, as determined by calling [Widget.canUpdate].
///
/// Typically implementations return a newly created constellation of widgets
/// that are configured with information from this widget's constructor and
/// from the given [BuildContext].
///
/// The given [BuildContext] contains information about the location in the
/// tree at which this widget is being built. For example, the context
/// provides the set of inherited widgets for this location in the tree. A
/// given widget might be built with multiple different [BuildContext]
/// arguments over time if the widget is moved around the tree or if the
/// widget is inserted into the tree in multiple places at once.
///
/// The implementation of this method must only depend on:
///
/// * the fields of the widget, which themselves must not change over time,
/// and
/// * any ambient state obtained from the `context` using
/// [BuildContext.dependOnInheritedWidgetOfExactType].
///
/// If a widget's [build] method is to depend on anything else, use a
/// [StatefulWidget] instead.
///
/// See also:
///
/// * [StatelessWidget], which contains the discussion on performance considerations.
Widget build(BuildContext context, WidgetRef ref);
@override
// ignore: library_private_types_in_public_api
_ConsumerState createState() => _ConsumerState();
}
class _ConsumerState extends ConsumerState<ConsumerWidget> {
@override
WidgetRef get ref => context as WidgetRef;
@override
Widget build(BuildContext context) {
return widget.build(context, ref);
}
}
/// A [StatefulWidget] that can read providers.
abstract class ConsumerStatefulWidget extends StatefulWidget {
/// A [StatefulWidget] that can read providers.
const ConsumerStatefulWidget({super.key});
@override
// ignore: no_logic_in_create_state
ConsumerState createState();
@override
ConsumerStatefulElement createElement() {
return ConsumerStatefulElement(this);
}
}
/// A [State] that has access to a [WidgetRef] through [ref], allowing
/// it to read providers.
abstract class ConsumerState<T extends ConsumerStatefulWidget>
extends State<T> {
/// An object that allows widgets to interact with providers.
late final WidgetRef ref = context as WidgetRef;
}
/// The [Element] for a [ConsumerStatefulWidget]
class ConsumerStatefulElement extends StatefulElement implements WidgetRef {
/// The [Element] for a [ConsumerStatefulWidget]
ConsumerStatefulElement(ConsumerStatefulWidget super.widget);
late ProviderContainer _container = ProviderScope.containerOf(this);
var _dependencies = <ProviderListenable, ProviderSubscription>{};
Map<ProviderListenable, ProviderSubscription>? _oldDependencies;
final _listeners = <ProviderSubscription>[];
List<_ListenManual>? _manualListeners;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final newContainer = ProviderScope.containerOf(this);
if (_container != newContainer) {
_container = newContainer;
for (final dependency in _dependencies.values) {
dependency.close();
}
_dependencies.clear();
}
}
@override
Widget build() {
// TODO disallow didChangeDependencies
try {
_oldDependencies = _dependencies;
for (var i = 0; i < _listeners.length; i++) {
_listeners[i].close();
}
_listeners.clear();
_dependencies = {};
return super.build();
} finally {
for (final dep in _oldDependencies!.values) {
dep.close();
}
_oldDependencies = null;
}
}
@override
Res watch<Res>(ProviderListenable<Res> target) {
return _dependencies.putIfAbsent(target, () {
final oldDependency = _oldDependencies?.remove(target);
if (oldDependency != null) {
return oldDependency;
}
return _container.listen<Res>(
target,
(_, __) => markNeedsBuild(),
);
}).read() as Res;
}
@override
void unmount() {
for (final dependency in _dependencies.values) {
dependency.close();
}
for (var i = 0; i < _listeners.length; i++) {
_listeners[i].close();
}
final manualListeners = _manualListeners?.toList();
if (manualListeners != null) {
for (final listener in manualListeners) {
listener.close();
}
_manualListeners = null;
}
super.unmount();
}
@override
void listen<T>(
ProviderListenable<T> provider,
void Function(T? previous, T value) listener, {
void Function(Object error, StackTrace stackTrace)? onError,
}) {
assert(
debugDoingBuild,
'ref.listen can only be used within the build method of a ConsumerWidget',
);
// We can't implement a fireImmediately flag because we wouldn't know
// which listen call was preserved between widget rebuild, and we wouldn't
// want to call the listener on every rebuild.
final sub = _container.listen<T>(provider, listener, onError: onError);
_listeners.add(sub);
}
@override
bool exists(ProviderBase<Object?> provider) {
return ProviderScope.containerOf(this, listen: false).exists(provider);
}
@override
T read<T>(ProviderListenable<T> provider) {
return ProviderScope.containerOf(this, listen: false).read(provider);
}
@override
State refresh<State>(Refreshable<State> provider) {
return ProviderScope.containerOf(this, listen: false).refresh(provider);
}
@override
void invalidate(ProviderOrFamily provider) {
_container.invalidate(provider);
}
@override
ProviderSubscription<T> listenManual<T>(
ProviderListenable<T> provider,
void Function(T? previous, T next) listener, {
void Function(Object error, StackTrace stackTrace)? onError,
bool fireImmediately = false,
}) {
final listeners = _manualListeners ??= [];
final sub = _ListenManual(
ProviderScope.containerOf(this, listen: false).listen(
provider,
listener,
onError: onError,
fireImmediately: fireImmediately,
),
this,
);
listeners.add(sub);
return sub;
}
@override
BuildContext get context => this;
}
class _ListenManual<T> implements ProviderSubscription<T> {
_ListenManual(this._subscription, this._element);
final ProviderSubscription<T> _subscription;
final ConsumerStatefulElement _element;
@override
void close() {
_subscription.close();
_element._manualListeners?.remove(this);
}
@override
T read() => _subscription.read();
}