-
Notifications
You must be signed in to change notification settings - Fork 28
/
mvc_pattern.dart
1291 lines (1103 loc) · 41.3 KB
/
mvc_pattern.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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// This library contains the classes necessary to develop apps using the MVC design pattern
/// separating the app's 'interface' from its 'business logic' and from its 'data source' if any.
///
/// Code samples can be found in the following links:
/// https://github.com/AndriousSolutions/mvc_pattern/tree/master/test
/// https://github.com/AndriousSolutions/mvc_pattern/blob/master/example/lib/main.dart
///
/// https://github.com/AndriousSolutions/mvc_pattern
///
library mvc_pattern;
/// Note: This license has also been called the "Simplified BSD License" and the "FreeBSD License".
/// See also the 2-clause BSD License.
///
/// Copyright 2018 www.andrioussolutions.com
///
/// Redistribution and use in source and binary forms, with or without modification,
/// are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
/// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
/// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
/// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
/// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
/// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
/// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import 'dart:math' show Random;
import 'dart:async' show Future;
import 'package:flutter/foundation.dart' show FlutterExceptionHandler;
import 'package:flutter/material.dart'
show
AppLifecycleState,
BuildContext,
FlutterError,
FlutterErrorDetails,
Key,
Locale,
State,
StatefulWidget,
VoidCallback,
Widget,
WidgetsBinding,
WidgetsBindingObserver,
mustCallSuper,
protected;
import 'package:flutter_test/flutter_test.dart'
show Future, TestWidgetsFlutterBinding;
/// Controller Class
/// Your 'working' class most concerned with the app's functionality.
abstract class ControllerMVC extends _StateObserver {
ControllerMVC([StateMVC state]) : super() {
addState(state);
}
String addState(StateMVC state) {
if (state == null) return '';
return state.add(this);
}
}
class _StateObserver with _StateSetter, StateListener {
/// Records the current error handler and supplies its own.
_StateObserver() : _oldOnError = _recOnError() {
/// If a tester is running. Don't switch out its error handler.
if (WidgetsBinding.instance is! TestWidgetsFlutterBinding) {
/// This allows you to place a breakpoint at 'onError(details)' to determine error location.
FlutterError.onError = (FlutterErrorDetails details) {
var thisOnError = onError;
/// Always favour a custom error handler.
if (thisOnError == StateMVC._defaultError &&
_oldOnError != StateMVC._defaultError) {
_oldOnError(details);
} else {
onError(details);
}
};
}
}
/// Save the current Error Handler.
final Function(FlutterErrorDetails details) _oldOnError;
StateMVC get stateMVC => _stateMVC;
/// Start using the getter, stateMVC
@deprecated
StateMVC get stateView => _stateMVC;
/// Overridden by mixin, StateSetter.
StateMVC _stateMVC;
List<ControllerMVC> listControllers(List<String> keys) =>
_stateMVC.listControllers(keys);
/// Provide the setState() function to external actors
void setState(fn) => _stateMVC?.setState(fn);
/// Allows external classes to 'refresh' or 'rebuild' the widget tree.
void refresh() => _stateMVC?.refresh();
// /// Add a listener fired 'before' the main controller runs.
// bool addBeforeListener(StateListener listener) =>
// _stateMVC?.addBeforeListener(listener);
//
// /// Add a listener fired 'after' the main controller runs.
// bool addAfterListener(StateListener listener) =>
// _stateMVC?.addAfterListener(listener);
//
// /// Add a listener fired 'after' the main controller runs.
// bool addListener(StateListener listener) =>
// _stateMVC?.addAfterListener(listener);
//
// /// Removes a specified listener.
// bool removeListener(StateListener listener) =>
// _stateMVC?.removeListener(listener);
/// Retrieve the 'before' listener by its unique key.
StateListener beforeListener(String key) => _stateMVC?.beforeListener(key);
/// Retrieve the 'after' listener by its unique key.
StateListener afterListener(String key) => _stateMVC?.afterListener(key);
/// Dispose the State Object and Controller references.
@mustCallSuper
void dispose() {
/// Return to the original error routine.
FlutterError.onError = _oldOnError;
/// The view association is severed.
_disposeState();
super.dispose();
}
/// Supply an 'error handler' routine to fire when an error occurs.
/// Allows the user to define their own with each Controller.
/// The default routine is to dump the error to the console.
// details.exception, details.stack
void onError(FlutterErrorDetails details) =>
FlutterError.dumpErrorToConsole(details);
}
mixin _StateSetter {
StateMVC _stateMVC;
final Set<StateMVC> _stateMVCSet = Set();
void _addState(StateMVC state) {
if (state == null) return;
_stateMVC = state;
_stateMVCSet.add(state);
}
bool _removeState(StateMVC state) {
if (state == null) return false;
if (state == _stateMVC) return _disposeState();
return _stateMVCSet.remove(state);
}
bool _disposeState() {
// Don't continue if null.
if (_stateMVC == null) return false;
// Remove the 'current' state
bool removed = _stateMVCSet.remove(_stateMVC);
// Reassign the last state object.
if (_stateMVCSet.isEmpty) {
_stateMVC = null;
} else {
_stateMVC = _stateMVCSet.last;
}
return removed;
}
}
/// Responsible for the event handling in all the Controllers, Listeners and Views.
mixin StateListener {
// Assigned an unique key.
String get keyId => _keyId;
String _keyId = Uuid().generateV4();
/// The framework will call this method exactly once.
/// Only when the [State] object is first created.
void initState() {
/// Override this method to perform initialization that depends on the
/// location at which this object was inserted into the tree.
/// (i.e. Subscribe to another object it depends on during [initState],
/// unsubscribe object and subscribe to a new object when it changes in
/// [didUpdateWidget], and then unsubscribe from the object in [dispose].
}
/// The framework calls this method whenever it removes this [State] object
/// from the tree.
void deactivate() {
/// The framework calls this method whenever it removes this [State] object
/// from the tree. It might reinsert it into another part of the tree.
/// Subclasses should override this method to clean up any links between
/// this object and other elements in the tree (e.g. if you have provided an
/// ancestor with a pointer to a descendant's [RenderObject]).
}
/// The framework calls this method when this [State] object will never
/// build again. The [State] object's lifecycle is terminated.
@mustCallSuper
void dispose() {
/// The framework calls this method when this [State] object will never
/// build again. The [State] object's lifecycle is terminated.
/// Subclasses should override this method to release any resources retained
/// by this object (e.g., stop any active animations).
}
/// Override this method to respond when the [widget] changes (e.g., to start
/// implicit animations).
void didUpdateWidget(StatefulWidget oldWidget) {
/// Override this method to respond when the [widget] changes (e.g., to start
/// implicit animations).
/// The framework always calls [build] after calling [didUpdateWidget], which
/// means any calls to [setState] in [didUpdateWidget] are redundant.
}
/// Called when the system puts the app in the background or returns the app to the foreground.
void didChangeAppLifecycleState(AppLifecycleState state) {
/// Passing these possible values:
/// AppLifecycleState.paused (may enter the suspending state at any time)
/// AppLifecycleState.resumed
/// AppLifecycleState.inactive (may be paused at any time)
/// AppLifecycleState.suspending (Android only)
}
/// Called when the application's dimensions change. For example,
/// when a phone is rotated.
void didChangeMetrics() {
/// Called when the application's dimensions change. For example,
/// when a phone is rotated.
///
/// In general, this is not overriden often as the layout system takes care of
/// automatically recomputing the application geometry when the application
/// size changes
///
/// This method exposes notifications from [Window.onMetricsChanged].
/// See sample code below. No need to call super if you override.
/// @override
/// void didChangeMetrics() {
/// setState(() { _lastSize = ui.window.physicalSize; });
/// }
}
/// Called when the platform's text scale factor changes.
void didChangeTextScaleFactor() {
/// Called when the platform's text scale factor changes.
///
/// This typically happens as the result of the user changing system
/// preferences, and it should affect all of the text sizes in the
/// application.
///
/// This method exposes notifications from [Window.onTextScaleFactorChanged].
/// See sample code below. No need to call super if you override.
/// @override
/// void didChangeTextScaleFactor() {
/// setState(() { _lastTextScaleFactor = ui.window.textScaleFactor; });
/// }
}
/// Called when the system tells the app that the user's locale has changed.
void didChangeLocale(Locale locale) {
/// Called when the system tells the app that the user's locale has
/// changed. For example, if the user changes the system language
/// settings.
///
/// This method exposes notifications from [Window.onLocaleChanged].
}
/// Called when the system is running low on memory.
void didHaveMemoryPressure() {
/// Called when the system is running low on memory.
///
/// This method exposes the `memoryPressure` notification from
/// [SystemChannels.system].
}
/// Called when the system changes the set of active accessibility features.
void didChangeAccessibilityFeatures() {
/// Called when the system changes the set of currently active accessibility
/// features.
///
/// This method exposes notifications from [Window.onAccessibilityFeaturesChanged].
}
/// Called when a dependency of this [State] object changes.
void didChangeDependencies() {
/// Called when a dependency of this [State] object changes.
///
/// For example, if the previous call to [build] referenced an
/// [InheritedWidget] that later changed, the framework would call this
/// method to notify this object about the change.
///
/// This method is also called immediately after [initState]. It is safe to
/// call [BuildContext.inheritFromWidgetOfExactType] from this method.
}
/// Called whenever the application is reassembled during debugging, for
/// example during hot reload.
void reassemble() {
/// Called whenever the application is reassembled during debugging, for
/// example during hot reload.
///
/// This method should rerun any initialization logic that depends on global
/// state, for example, image loading from asset bundles (since the asset
/// bundle may have changed).
}
}
/// Main State Object seen as the 'StateView.'
abstract class StateMVC<T extends StatefulWidget> extends State<StatefulWidget>
with WidgetsBindingObserver, _ControllerListing, _StateListeners
implements StateListener {
/// The View!
Widget build(BuildContext context);
/// You need to be able access the widget.
T get widget => super.widget;
/// Record the 'default' error handler for Flutter.
static final FlutterExceptionHandler _defaultError = FlutterError.onError;
/// With an optional Controller parameter, this constructor imposes its own Errror Handler.
StateMVC([this._controller]) : _oldOnError = _recOnError() {
/// If a tester is running. Don't switch out its error handler.
if (WidgetsBinding.instance is! TestWidgetsFlutterBinding) {
/// This allows one to place a breakpoint at 'onError(details)' to determine error location.
FlutterError.onError = (FlutterErrorDetails details) {
Function(FlutterErrorDetails details) thisOnError = onError;
/// Always favour a custom error handler.
if (thisOnError == _defaultError && _oldOnError != _defaultError) {
_oldOnError(details);
} else {
onError(details);
}
};
}
/// IMPORTANT! Assign itself to stateView before adding any Controller. -gp
/// Any subsequent calls to add() will be assigned, stateMVC.
_stateMVC = this;
add(_controller);
}
ControllerMVC _controller;
/// Save the original Error Handler.
final Function(FlutterErrorDetails details) _oldOnError;
/// Provide the 'main' controller to this 'State View.'
/// If _controller == null, get the 'first assigned' controller.
ControllerMVC get controller {
if (_controller == null) _controller = firstCon;
return _controller;
}
/// Retrieve a Controller by its a unique String identifier.
ControllerMVC controllerById(String keyId) => super._con(keyId);
/// Add a specific Controller to this View.
/// Returns the Controller's unique String identifier.
String add(ControllerMVC c) {
if (c == null) return '';
/// It may have been a listener. Can't be both.
removeListener(c);
return super.add(c);
}
void addList(List<ControllerMVC> list) {
if (list == null) return;
/// It may have been a listener. Can't be both.
list.forEach((ControllerMVC con) => removeListener(con));
return super.addList(list);
}
/// The Unique key identifier for this State object.
String get keyId => _keyId;
/// Contains the unique String identifier.
String _keyId = Uuid().generateV4();
/// May be set false to prevent unnecessary 'rebuilds'.
bool _rebuildAllowed = true;
/// May be set true to request a 'rebuild.'
bool _rebuildRequested = false;
/// The framework will call this method exactly once.
/// Only when the [State] object is first created.
@protected
@override
@mustCallSuper
void initState() {
/// Override this method to perform initialization that depends on the
/// location at which this object was inserted into the tree.
/// (i.e. Subscribe to another object it depends on during [initState],
/// unsubscribe object and subscribe to a new object when it changes in
/// [didUpdateWidget], and then unsubscribe from the object in [dispose].
super.initState();
WidgetsBinding.instance.addObserver(this);
AppMVC._addStateMVC(this);
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
// _controllerList.forEach((ControllerMVC con) => con._widget = widget);
_beforeList.forEach((StateListener listener) => listener.initState());
_controllerList.forEach((ControllerMVC con) => con.initState());
_afterList.forEach((StateListener listener) => listener.initState());
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// The framework calls this method whenever it removes this [State] object
/// from the tree.
@protected
@override
@mustCallSuper
void deactivate() {
/// The framework calls this method whenever it removes this [State] object
/// from the tree. It might reinsert it into another part of the tree.
/// Subclasses should override this method to clean up any links between
/// this object and other elements in the tree (e.g. if you have provided an
/// ancestor with a pointer to a descendant's [RenderObject]).
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList.forEach((StateListener listener) => listener.deactivate());
_controllerList.forEach((ControllerMVC con) => con.deactivate());
_afterList.forEach((StateListener listener) => listener.deactivate());
super.deactivate();
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// The framework calls this method when this [State] object will never
/// build again.
@protected
@override
@mustCallSuper
void dispose() {
/// The [State] object's lifecycle is terminated.
/// Subclasses should override this method to release any resources retained
/// by this object (e.g., stop any active animations).
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList.forEach((StateListener listener) => listener.dispose());
_controllerList.forEach((ControllerMVC con) => con.dispose());
_disposeControllerListing();
_afterList.forEach((StateListener listener) => listener.dispose());
_disposeStateEventList();
/// Should not be 'rebuilding' anyway. This Widget is going away.
_rebuildAllowed = true;
_rebuildRequested = false;
WidgetsBinding.instance.removeObserver(this);
/// Remove any 'Controller' reference
_controller = null;
/// Return the original error routine.
FlutterError.onError = _oldOnError;
super.dispose();
}
/// Override this method to respond when the [widget] changes (e.g., to start
/// implicit animations).
@protected
@override
@mustCallSuper
void didUpdateWidget(StatefulWidget oldWidget) {
/// The framework always calls [build] after calling [didUpdateWidget], which
/// means any calls to [setState] in [didUpdateWidget] are redundant.
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList.forEach(
(StateListener listener) => listener.didUpdateWidget(oldWidget));
_controllerList
.forEach((ControllerMVC con) => con.didUpdateWidget(oldWidget));
_afterList.forEach(
(StateListener listener) => listener.didUpdateWidget(oldWidget));
super.didUpdateWidget(oldWidget);
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// Called when the system puts the app in the background or returns the app to the foreground.
@protected
@override
@mustCallSuper
void didChangeAppLifecycleState(AppLifecycleState state) {
/// Passing either the values AppLifecycleState.paused or AppLifecycleState.resumed.
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList.forEach(
(StateListener listener) => listener.didChangeAppLifecycleState(state));
_controllerList
.forEach((ControllerMVC con) => con.didChangeAppLifecycleState(state));
_afterList.forEach(
(StateListener listener) => listener.didChangeAppLifecycleState(state));
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// Called when the application's dimensions change. For example,
/// when a phone is rotated.
@protected
@override
void didChangeMetrics() {
/// In general, this is not overridden often as the layout system takes care of
/// automatically recomputing the application geometry when the application
/// size changes
///
/// This method exposes notifications from [Window.onMetricsChanged].
/// See sample code below. No need to call super if you override.
/// @override
/// void didChangeMetrics() {
/// setState(() { _lastSize = ui.window.physicalSize; });
/// }
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList
.forEach((StateListener listener) => listener.didChangeMetrics());
_controllerList.forEach((ControllerMVC con) => con.didChangeMetrics());
_afterList.forEach((StateListener listener) => listener.didChangeMetrics());
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// Called when the platform's text scale factor changes.
@protected
@override
void didChangeTextScaleFactor() {
///
/// This typically happens as the result of the user changing system
/// preferences, and it should affect all of the text sizes in the
/// application.
///
/// This method exposes notifications from [Window.onTextScaleFactorChanged].
/// See sample code below. No need to call super if you override.
/// @override
/// void didChangeTextScaleFactor() {
/// setState(() { _lastTextScaleFactor = ui.window.textScaleFactor; });
/// }
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList.forEach(
(StateListener listener) => listener.didChangeTextScaleFactor());
_controllerList
.forEach((ControllerMVC con) => con.didChangeTextScaleFactor());
_afterList.forEach(
(StateListener listener) => listener.didChangeTextScaleFactor());
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// Called when the system tells the app that the user's locale has
/// changed. For example, if the user changes the system language
/// settings.
@protected
//@override
void didChangeLocale(Locale locale) {
///
/// This method exposes notifications from [Window.onLocaleChanged].
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList
.forEach((StateListener listener) => listener.didChangeLocale(locale));
_controllerList.forEach((ControllerMVC con) => con.didChangeLocale(locale));
_afterList
.forEach((StateListener listener) => listener.didChangeLocale(locale));
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// Called when the system is running low on memory.
@protected
@override
void didHaveMemoryPressure() {
///
/// This method exposes the `memoryPressure` notification from
/// [SystemChannels.system].
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList
.forEach((StateListener listener) => listener.didHaveMemoryPressure());
_controllerList.forEach((ControllerMVC con) => con.didHaveMemoryPressure());
_afterList
.forEach((StateListener listener) => listener.didHaveMemoryPressure());
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// Called when the system changes the set of currently active accessibility
/// features.
@protected
@override
void didChangeAccessibilityFeatures() {
///
/// This method exposes notifications from [Window.onAccessibilityFeaturesChanged].
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList.forEach(
(StateListener listener) => listener.didChangeAccessibilityFeatures());
_controllerList
.forEach((ControllerMVC con) => con.didChangeAccessibilityFeatures());
_afterList.forEach(
(StateListener listener) => listener.didChangeAccessibilityFeatures());
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// A flag indicating this is the very first build.
bool _firstBuild = true;
/// Called when a dependency of this [State] object changes.
@protected
@override
@mustCallSuper
void didChangeDependencies() {
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList
.forEach((StateListener listener) => listener.didChangeDependencies());
_controllerList.forEach((ControllerMVC con) => con.didChangeDependencies());
_afterList
.forEach((StateListener listener) => listener.didChangeDependencies());
super.didChangeDependencies();
_rebuildAllowed = true;
if (_rebuildRequested && !_firstBuild) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
/// Not the first build now.
_firstBuild = false;
}
/// Called whenever the application is reassembled during debugging, for
/// example during hot reload.
@protected
@mustCallSuper
@override
void reassemble() {
/// No 'setState()' functions are allowed to fully function at this point.
_rebuildAllowed = false;
_beforeList.forEach((StateListener listener) => listener.reassemble());
_controllerList.forEach((ControllerMVC con) => con.reassemble());
_afterList.forEach((StateListener listener) => listener.reassemble());
super.reassemble();
_rebuildAllowed = true;
if (_rebuildRequested) {
_rebuildRequested = false;
/// Perform a 'rebuild' if requested.
refresh();
}
}
/// Allows 'external' routines can call this function.
// Note not 'protected' and so can be called by 'anyone.' -gp
void setState(VoidCallback fn) {
if (_rebuildAllowed) {
/// Call the State object's setState() function.
super.setState(fn);
} else {
/// Can't rebuild at this moment but at least make the request.
_rebuildRequested = true;
}
}
/// Allows the user to call setState() within the Controller.
// Note not 'protected' and so can be called by 'anyone.' -gp
void refresh() {
if (mounted) {
/// Refresh the interface by 'rebuilding' the Widget Tree
setState(() {});
}
}
/// Supply an 'error handler' routine to fire when an error occurs.
/// Allows the user to define their own with each Controller.
/// The default routine is to dump the error to the console.
// details.exception, details.stack
@protected
void onError(FlutterErrorDetails details) =>
FlutterError.dumpErrorToConsole(details);
}
/// Records 'the current' error handler.
Function(FlutterErrorDetails details) _recOnError() {
var func;
/// If the 'current' Error Handler is not the 'default' routine, you better save it.
if (FlutterError.onError != StateMVC._defaultError) {
func = FlutterError.onError;
} else {
func = StateMVC._defaultError;
}
return func;
}
/// Add, List, and Remove Listeners.
mixin _StateListeners {
List<StateListener> get _beforeList => _listenersBefore.toList();
List<StateListener> beforeList(List<String> keys) {
return _getList(keys, _listenersBefore);
}
final Set<StateListener> _listenersBefore = Set();
List<StateListener> get _afterList => _listenersAfter.toList();
List<StateListener> afterList(List<String> keys) {
return _getList(keys, _listenersAfter);
}
List<StateListener> _getList(List<String> keys, Set<StateListener> set) {
List<StateListener> list = List();
if (keys == null || keys.isEmpty) return list;
set.map((StateListener evt) {
for (String key in keys) {
if (evt._keyId == key) {
list.add(evt);
keys.remove(key);
break;
}
}
});
return list;
}
final Set<StateListener> _listenersAfter = Set();
/// Add a listener fired 'before' the main controller runs.
bool addBeforeListener(StateListener listener) =>
_listenersBefore.add(listener);
/// Add a listener fired 'after' the main controller runs.
bool addAfterListener(StateListener listener) =>
_listenersAfter.add(listener);
/// Add a listener fired 'after' the main controller runs.
bool addListener(StateListener listener) => addAfterListener(listener);
bool removeListener(StateListener listener) {
bool removed = _listenersBefore.remove(listener);
if (_listenersAfter.remove(listener)) removed = true;
return removed;
}
bool beforeContains(StateListener listener) =>
_listenersBefore.contains(listener);
bool afterContains(StateListener listener) =>
_listenersAfter.contains(listener);
StateListener beforeListener(String key) =>
_getStateEvents(key, _listenersBefore);
StateListener afterListener(String key) =>
_getStateEvents(key, _listenersAfter);
StateListener _getStateEvents(String key, Set<StateListener> set) {
StateListener se;
if (key == null || key.isEmpty) return se;
set.map((StateListener evt) {
if (evt._keyId == key) {
se = evt;
return;
}
});
return se;
}
void _disposeStateEventList() {
_listenersBefore.clear();
_listenersAfter.clear();
}
}
class _ControllerListing {
StateMVC _stateMVC;
// Keep it private to allow subclasses to use 'con.'
ControllerMVC _con(String keyId) {
if (keyId == null || keyId.isEmpty) return null;
return _map[keyId];
}
void addList(List<ControllerMVC> list) =>
list.forEach((ControllerMVC con) => add(con));
List<ControllerMVC> listControllers(List<String> keys) =>
controllers(keys).values.toList();
/// Never supply a public list of Controllers. User must know the key identifier(s).
List<ControllerMVC> get _controllerList => _asList; //_controllers.asList;
Map<String, ControllerMVC> controllers(List<String> keys) {
Map<String, ControllerMVC> controllers = {};
keys.forEach(
(String key) => controllers[key] = map[key]); //_controllers.map[key]);
return controllers;
}
final Map<String, ControllerMVC> _map = Map();
Map<String, ControllerMVC> get map => _map;
List<ControllerMVC> get _asList => _map.values.toList();
String add(ControllerMVC con) {
if (con == null) return '';
/// This connects the Controller to this View!
con._addState(_stateMVC);
/// It's already there?! Return its key.
return (contains(con)) ? con._keyId : addConId(con);
}
bool remove(String keyId) {
var con = _map[keyId];
var there = con != null;
if (there) {
con._removeState(_stateMVC);
_map.remove(keyId);
}
return there;
}
ControllerMVC get firstCon => _asList.first;
bool contains(ControllerMVC con) => _map.containsValue(con);
void _disposeControllerListing() => _map.clear();
String addConId(ControllerMVC con) {
String keyId = _addKeyId(con);
_map[keyId] = con;
return keyId;
}
}
String _addKeyId(_StateObserver sv) {
String keyId = sv._keyId;
/// May already have been assigned a key.
if (keyId.isEmpty) {
keyId = Uuid().generateV4();
sv._keyId = keyId;
}
return keyId;
}
/// View Class
/// Extend and implement its build() function to compose its interface.
abstract class ViewMVC extends _StateObserver with _ControllerListing {
/// Implement this build() function to compose the View's interface.
Widget build(BuildContext context);
/// Must take in one Controller when this Class instantiates.
ViewMVC(this.controller) {
_addKeyId(this);
// Add this Controller to the Controller Listing!
add(controller);
}
final ControllerMVC controller;
/// Retrieve a Controller from this View.
/// Retrieved by using a unique String identifier.
ControllerMVC con(String keyId) {
assert(_stateMVC != null, "Pass this ViewMVC to a StateViewMVC!");
return super._con(keyId);
}
/// Add a Controller to this View.
@override
String add(ControllerMVC c) {
assert(_stateMVC != null, "Pass this ViewMVC to a StateViewMVC!");
return super.add(c);
}
/// Called to 'clean up' the List of Controllers and such
/// associated with this View.
@override
void dispose() {
_disposeControllerListing();
super.dispose();
}
}
/// The State Object with an Error Handler in its build() function.
abstract class StateViewMVC<T extends StatefulWidget> extends StateMVC<T> {
/// Takes in a View and passes the View's Controller to the parent class.
StateViewMVC(this.view) : super(view.controller) {
assert(view != null, "View can't be null! Pass a ViewMVC to StateViewMVC.");
/// IMPORTANT! Add the View's controllers first before calling setter. -gp
addList(view._controllerList);
/// Clear any controllers associated.
view._disposeControllerListing();
/// IMPORTNANT! This setter connects the State Object!
view._stateMVC = this;
view._addState(this);
}
final ViewMVC view;
/// Supply the every Widget returned by the build() function.
Widget get buildWidget => _widget;
Widget _widget;
Function(FlutterErrorDetails details) _currentOnError;
/// The build function wrapped in an Error Handler to prevent
/// crashes from unruly Controllers and or Listeners.
@override
@protected
Widget build(BuildContext context) {
/// Save the current Error Handler if any.
_currentOnError = FlutterError.onError;
/// If a tester is running. Don't switch out its error handler.
if (WidgetsBinding.instance is! TestWidgetsFlutterBinding) {
FlutterError.onError = (FlutterErrorDetails details) {
/// This allows one to place a breakpoint at 'onError(details)' to determine error location.
var thisOnError = onError;