Line data Source code
1 : import 'package:flutter/foundation.dart';
2 :
3 : typedef AsyncChangeHandler<T> = Future<T> Function();
4 :
5 : typedef ChangeHandler<T> = T Function();
6 :
7 : class CollectionChangeNotifier extends ChangeNotifier {
8 : bool _paused = false;
9 :
10 : /// Pause notifications until after an asynchronous handler has completed.
11 : /// If [notifyAfter] is `true`, then listeners will automatically be notified
12 : /// after the callback completes. Otherwise, you must notify the listeners;
13 5 : Future<T> pauseNotificationsAsync<T>(AsyncChangeHandler<T> handler,
14 : [bool notifyAfter = false]) async {
15 5 : final prevState = _paused;
16 5 : _paused = true;
17 :
18 10 : final result = await handler();
19 5 : _paused = prevState;
20 :
21 : if (notifyAfter) {
22 4 : notifyListeners();
23 : }
24 :
25 : return result;
26 : }
27 :
28 : /// Pause notifications until after a synchronous handler has completed.
29 : /// If [notifyAfter] is `true`, then listeners will automatically be notified
30 : /// after the callback completes. Otherwise, you must notify the listeners;
31 5 : T pauseNotifications<T>(ChangeHandler<T> handler,
32 : [bool notifyAfter = false]) {
33 5 : final prevState = _paused;
34 5 : _paused = true;
35 5 : final result = handler();
36 5 : _paused = prevState;
37 :
38 : if (notifyAfter) {
39 5 : notifyListeners();
40 : }
41 :
42 : return result;
43 : }
44 :
45 : /// Notify all the listeners, respecting our paused state falg
46 6 : @override
47 : void notifyListeners() {
48 6 : if (!_paused) {
49 6 : super.notifyListeners();
50 : }
51 : }
52 : }
|