-
Notifications
You must be signed in to change notification settings - Fork 9
/
app.dart
870 lines (748 loc) · 25.4 KB
/
app.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
///
/// Copyright (C) 2019 Andrious Solutions
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Created 09 Feb 2019
///
///
import 'dart:async' show Future, StreamSubscription;
import 'dart:ui' as ui show SingletonFlutterWindow;
// Replace 'dart:io' for Web applications
import 'package:universal_platform/universal_platform.dart';
import 'package:flutter/foundation.dart' show FlutterExceptionHandler, kIsWeb;
import 'package:package_info_plus/package_info_plus.dart' show PackageInfo;
import 'package:connectivity_plus/connectivity_plus.dart'
show Connectivity, ConnectivityResult;
import 'package:mvc_pattern/mvc_pattern.dart' as mvc;
import 'package:mvc_application/model.dart';
import 'package:mvc_application/view.dart' as v;
import 'package:mvc_application/controller.dart'
show ControllerMVC, DeviceInfo, HandleError;
/// This class is available throughout the app
/// Readily supplies static properties about the App.
class App {
/// Supply an error handler to the App.
factory App({
FlutterExceptionHandler? errorHandler,
ErrorWidgetBuilder? errorScreen,
v.ReportErrorHandler? errorReport,
bool allowNewHandlers = true,
}) =>
_this ??= App._(errorHandler, errorScreen, errorReport, allowNewHandlers);
App._(
FlutterExceptionHandler? errorHandler,
ErrorWidgetBuilder? errorScreen,
v.ReportErrorHandler? errorReport,
bool allowNewHandlers,
) {
_errorHandler = v.AppErrorHandler(
handler: errorHandler,
builder: errorScreen,
report: errorReport,
allowNewHandlers: allowNewHandlers,
);
}
static App? _this;
/// Returns the current Error Handler.
static v.AppErrorHandler? get errorHandler => _errorHandler;
static v.AppErrorHandler? _errorHandler;
/// Dispose the App properties.
void dispose() {
_connectivitySubscription?.cancel();
_connectivitySubscription = null;
_packageInfo = null;
_themeData = null;
// _appWidget = null;
_appState = null;
// Restore the original error handling.
_errorHandler!.dispose();
_errorHandler = null;
}
/// Assign the class with the AppState object.
bool setAppState(v.AppState? vw) {
// Don't continue if an app called an app.
final set = vw != null && (_appState == null || hotReload);
if (set) {
//
_appState = vw;
// Assign the 'app' object to the app's view
vw.app = this;
}
return set;
}
/// The App State object.
static v.AppState? get vw => _appState;
//todo: Change to 'late' instead and redo everything reference.
static v.AppState? _appState;
/// App-level error handling.
static void onError(FlutterErrorDetails details) {
// Call the App's 'current' error handler.
final handler = errorHandler?.flutterExceptionHandler;
if (handler != null) {
handler(details);
} else {
// Call Flutter's default error handler.
FlutterError.presentError(details);
}
}
/// App-level error handling if async operation at start up fails
void onAsyncError(AsyncSnapshot<bool> snapshot) {
final dynamic exception = snapshot.error;
final details = FlutterErrorDetails(
exception: exception,
stack: exception is Error ? exception.stackTrace : null,
library: 'app_statefulwidget',
context: ErrorDescription('while getting ready with FutureBuilder Async'),
);
onError(details);
}
/// Collect the device's information.
static Future<void> getDeviceInfo() async {
_packageInfo = await PackageInfo.fromPlatform();
// Collect Device Information
await DeviceInfo.initAsync();
}
/// Passed to the CupertinoApp or MaterialApp
@Deprecated('Prone to misuse. Can not be used more than once.')
static final widgetsAppKey = GlobalKey(debugLabel: 'mvc_app');
/// Determine if the App initialized successfully.
// ignore: unnecessary_getters_setters
static bool? get isInit => _isInit;
/// Set the init only once.
// ignore: unnecessary_getters_setters
static set isInit(bool? init) => _isInit ??= init;
static bool? _isInit;
/// Flag to set hot reload from now on.
// ignore: unnecessary_getters_setters
static bool get hotReload => _hotReload;
/// Once set, it will always hot reload.
// ignore: unnecessary_getters_setters
static set hotReload(bool hotReload) {
// It doesn't accept false.
// i.e. Once true, it stays true.
if (!hotReload) {
return;
}
_hotReload = hotReload;
}
static bool _hotReload = false;
// Use Material UI when explicitly specified or even when running in iOS
/// Indicates if the App is running the Material interface theme.
static bool get useMaterial =>
(_appState != null && _appState!.useMaterial!) ||
(UniversalPlatform.isAndroid &&
(_appState == null || !_appState!.switchUI!)) ||
(UniversalPlatform.isIOS && (_appState == null || _appState!.switchUI!));
// Use Cupertino UI when explicitly specified or even when running in Android
/// Indicates if the App is running the Cupertino interface theme.
static bool get useCupertino =>
(_appState != null && _appState!.useCupertino!) ||
(UniversalPlatform.isIOS &&
(_appState == null || !_appState!.switchUI!)) ||
(UniversalPlatform.isAndroid &&
(_appState == null || _appState!.switchUI!));
/// Explicitly change to a particular interface.
static void changeUI(String ui) => _appState?.changeUI(ui);
/// Flutter application's main window.
static ui.SingletonFlutterWindow get mainWindow =>
_window ??= WidgetsBinding.instance.window;
static ui.SingletonFlutterWindow? _window;
/// Return the navigator key used by the App's View.
static GlobalKey<NavigatorState>? get navigatorKey => _appState?.navigatorKey;
static set navigatorKey(GlobalKey<NavigatorState>? v) {
if (v != null) {
_appState?.navigatorKey = v;
}
}
/// Return the navigator key used by the App's View.
static GlobalKey<ScaffoldMessengerState>? get scaffoldMessengerKey =>
_appState?.scaffoldMessengerKey;
static set scaffoldMessengerKey(GlobalKey<ScaffoldMessengerState>? v) {
if (v != null) {
_appState?.scaffoldMessengerKey = v;
}
}
/// Returns the routes used by the App's View.
static Map<String, WidgetBuilder>? get routes => _appState?.routes;
static set routes(Map<String, WidgetBuilder>? v) {
if (v != null) {
_appState?.routes = v;
}
}
/// Returns to the initial route used by the App's View.
static String? get initialRoute => _appState?.initialRoute;
static set initialRoute(String? v) {
if (v != null) {
_appState?.initialRoute = v;
}
}
/// The route generator used when the app is navigated to a named route.
static RouteFactory? get onGenerateRoute => _appState?.onGenerateRoute;
static set onGenerateRoute(RouteFactory? v) {
if (v != null) {
_appState?.onGenerateRoute = v;
}
}
/// Called when [onGenerateRoute] fails except for the [initialRoute].
static RouteFactory? get onUnknownRoute => _appState?.onUnknownRoute;
static set onUnknownRoute(RouteFactory? v) {
if (v != null) {
_appState?.onUnknownRoute = v;
}
}
/// The list of observers for the [Navigator] for this app.
static List<NavigatorObserver>? get navigatorObservers =>
_appState?.navigatorObservers;
static set navigatorObservers(List<NavigatorObserver>? v) {
if (v != null) {
_appState?.navigatorObservers = v;
}
}
/// if neither [routes], or [onGenerateRoute] was passed.
static TransitionBuilder? get builder => _appState?.builder;
static set builder(TransitionBuilder? v) {
if (v != null) {
_appState?.builder = v;
}
}
/// Returns the title for the App's View.
static String? get title => _appState?.title;
static set title(String? v) {
if (v != null) {
_appState?.title = v;
}
}
/// Routine used to generate the App's title.
static GenerateAppTitle? get onGenerateTitle => _appState?.onGenerateTitle;
static set onGenerateTitle(GenerateAppTitle? v) {
if (v != null) {
_appState?.onGenerateTitle = v;
}
}
// Allow it to be assigned null.
/// The App's current Material theme.
static ThemeData? get themeData => _themeData;
static set themeData(dynamic value) {
if (value == null) {
return;
}
if (value is ThemeData) {
_themeData = value;
} else if (value is CupertinoThemeData) {
// Ignore the value
} else if (value is! ColorSwatch) {
// Ignore the value
} else if (_themeData == null) {
_themeData = ThemeData(
primaryColor: value,
);
} else {
_themeData = _themeData?.copyWith(
primaryColor: value,
);
}
}
static ThemeData? _themeData;
/// The Apps's current Cupertino theme.
static CupertinoThemeData? get iOSTheme => _iOSTheme;
static CupertinoThemeData? _iOSTheme;
static set iOSTheme(dynamic value) {
if (value == null) {
return;
}
if (value is CupertinoThemeData) {
_iOSTheme = value;
} else if (value is ThemeData) {
_iOSTheme = MaterialBasedCupertinoThemeData(materialTheme: value);
} else if (value is! ColorSwatch) {
// Ignore the value
} else if (_iOSTheme == null) {
_iOSTheme = CupertinoThemeData(
primaryColor: value,
);
} else {
_iOSTheme = _iOSTheme?.copyWith(
primaryColor: value,
);
}
}
/// Set the App's general color theme supplying a [ColorSwatch] value.
static ColorSwatch<int?>? setThemeData([ColorSwatch<int?>? value]) {
//
if (!Prefs.ready()) {
return value;
}
if (value != null) {
Prefs.setInt(
'colorTheme',
Colors.primaries.indexOf(value as MaterialColor),
);
} else {
final swatch = Prefs.getInt('colorTheme', -1);
// If never set in the first place, ignore
if (swatch > -1) {
value = Colors.primaries[swatch];
}
}
if (value != null) {
/// Assign the colour to the floating button as well.
themeData = ThemeData(
primarySwatch: value as MaterialColor,
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: value,
),
);
iOSTheme = value;
}
return value;
}
/// Returns the Color passed to the App's View.
static Color? get color => _appState?.color;
static set color(Color? v) {
if (v != null) {
_appState?.color = v;
}
}
/// Returns the App's current locale.
static Locale? get locale =>
_appState?.locale ??= Localizations.maybeLocaleOf(context!) ??
_resolveLocales(
mainWindow.locales,
_appState?.supportedLocales,
);
/// Set the App's Locale
/// If 'supportedLocales' are specified, this Locale must be among them.
static set locale(Locale? locale) {
if (locale != null && v.L10n.setLocale(locale)) {
_appState?.locale = locale;
}
}
/// Determine the locale used by the Mobile phone.
static Locale? _resolveLocales(
List<Locale>? preferredLocales,
Iterable<Locale>? supportedLocales,
) {
// Attempt to use localeListResolutionCallback.
if (_appState?.localeListResolutionCallback != null) {
final locales = _appState?.supportedLocales;
final locale =
_appState?.localeListResolutionCallback!(preferredLocales, locales!);
if (locale != null) {
return locale;
}
}
final preferred = preferredLocales != null && preferredLocales.isNotEmpty
? preferredLocales.first
: null;
// localeListResolutionCallback failed, falling back to localeResolutionCallback.
if (_appState?.localeResolutionCallback != null) {
final locales = _appState?.supportedLocales;
final locale = _appState?.localeResolutionCallback!(
preferred,
locales!,
);
if (locale != null) {
return locale;
}
}
// Both callbacks failed, falling back to default algorithm.
// return basicLocaleListResolution(preferredLocales, supportedLocales);
return preferred;
}
/// Returns the App's current localizations delegates.
static Iterable<LocalizationsDelegate<dynamic>>? get localizationsDelegates =>
_appState?.localizationsDelegates;
static set localizationsDelegates(
Iterable<LocalizationsDelegate<dynamic>>? v) {
if (v != null) {
_appState?.localizationsDelegates = v;
}
}
/// Resolves the App's locale.
static LocaleResolutionCallback? get localeResolutionCallback =>
_appState?.localeResolutionCallback;
static set localeResolutionCallback(LocaleResolutionCallback? v) {
if (v != null) {
_appState?.localeResolutionCallback = v;
}
}
/// getter, supportedLocales, returns a List of the App's locales.
/// More flexible than an iteration.
static List<Locale>? get supportedLocales => _appState?.supportedLocales;
static set supportedLocales(List<Locale>? v) {
if (v != null) {
_appState?.supportedLocales = v;
}
}
/// If true, it paints a grid overlay on Material apps.
static bool? get debugShowMaterialGrid => _appState?.debugShowMaterialGrid;
static set debugShowMaterialGrid(bool? v) {
if (v != null) {
_appState?.debugShowMaterialGrid = v;
}
}
/// If true, it turns on a performance overlay.
static bool? get showPerformanceOverlay => _appState?.showPerformanceOverlay;
static set showPerformanceOverlay(bool? v) {
if (v != null) {
_appState?.showPerformanceOverlay = v;
}
}
/// Checkerboard raster cache to speed up overall rendering.
static bool? get checkerboardRasterCacheImages =>
_appState?.checkerboardRasterCacheImages;
static set checkerboardRasterCacheImages(bool? v) {
if (v != null) {
_appState?.checkerboardRasterCacheImages = v;
}
}
/// Checkerboard layers rendered offscreen bitmaps.
static bool? get checkerboardOffscreenLayers =>
_appState?.checkerboardOffscreenLayers;
static set checkerboardOffscreenLayers(bool? v) {
if (v != null) {
_appState?.checkerboardOffscreenLayers = v;
}
}
/// Shows an overlay of accessibility information
static bool? get showSemanticsDebugger => _appState?.showSemanticsDebugger;
static set showSemanticsDebugger(bool? v) {
if (v != null) {
_appState?.showSemanticsDebugger = v;
}
}
/// Shows a little "DEBUG" banner in checked mode.
static bool? get debugShowCheckedModeBanner =>
_appState?.debugShowCheckedModeBanner;
static set debugShowCheckedModeBanner(bool? v) {
if (v != null) {
_appState?.debugShowCheckedModeBanner = v;
}
}
/// Each RenderBox to paint a box around its bounds.
static bool? get debugPaintSizeEnabled => _appState?.debugPaintSizeEnabled;
static set debugPaintSizeEnabled(bool? v) {
if (v != null) {
_appState?.debugPaintSizeEnabled = v;
}
}
/// RenderBox paints a line at its baselines.
static bool? get debugPaintBaselinesEnabled =>
_appState?.debugPaintBaselinesEnabled;
static set debugPaintBaselinesEnabled(bool? v) {
if (v != null) {
_appState?.debugPaintBaselinesEnabled = v;
}
}
/// Objects flash while they are being tapped.
static bool? get debugPaintPointersEnabled =>
_appState?.debugPaintPointersEnabled;
static set debugPaintPointersEnabled(bool? v) {
if (v != null) {
_appState?.debugPaintPointersEnabled = v;
}
}
/// Layer paints a box around its bound.
static bool? get debugPaintLayerBordersEnabled =>
_appState?.debugPaintLayerBordersEnabled;
static set debugPaintLayerBordersEnabled(bool? v) {
if (v != null) {
_appState?.debugPaintLayerBordersEnabled = v;
}
}
/// Overlay a rotating set of colors when repainting layers in checked mode.
static bool? get debugRepaintRainbowEnabled =>
_appState?.debugRepaintRainbowEnabled;
static set debugRepaintRainbowEnabled(bool? v) {
if (v != null) {
_appState?.debugRepaintRainbowEnabled = v;
}
}
/// The running platform
static TargetPlatform? get platform {
if (_platform == null && context != null) {
_platform = Theme.of(context!).platform;
}
return _platform;
}
static TargetPlatform? _platform;
// Application information
static PackageInfo? _packageInfo;
/// The Name of the App.
static String? get appName => _packageInfo?.appName;
/// The 'Package Name' of the App.
static String? get packageName => _packageInfo?.packageName;
/// The current version of the App.
static String? get version => _packageInfo?.version;
/// The build number of the App.
static String? get buildNumber => _packageInfo?.buildNumber;
/// Determines if running in an IDE or in production.
static bool get inDebugger => _appState?.inDebugger ?? false;
/// Refresh the root State object with the passed function.
static void setState(VoidCallback fn) => _appState?.setState(fn);
/// Refresh the root State object.
static void refresh() => _appState?.refresh();
/// Rebuild the InheritedWidget of the 'closes' InheritedStateMVC object if any.
static void buildInherited() => _appState?.buildInherited();
/// Display the SnackBar
static void snackBar({
Key? key,
required Widget content,
Color? backgroundColor,
double? elevation,
EdgeInsetsGeometry? margin,
EdgeInsetsGeometry? padding,
double? width,
ShapeBorder? shape,
SnackBarBehavior? behavior,
SnackBarAction? action,
Duration? duration,
Animation<double>? animation,
VoidCallback? onVisible,
DismissDirection dismissDirection = DismissDirection.down,
}) {
final state = ScaffoldMessenger.maybeOf(context!);
state?.showSnackBar(
SnackBar(
key: key,
content: content,
backgroundColor: backgroundColor,
elevation: elevation,
margin: margin,
padding: padding,
width: width,
shape: shape,
behavior: behavior,
action: action,
duration: duration ?? const Duration(milliseconds: 4000),
animation: animation,
onVisible: onVisible,
dismissDirection: dismissDirection,
),
);
}
/// Catch and explicitly handle the error.
static void catchError(Object ex) {
if (ex is! Exception) {
ex = Exception(ex.toString());
}
_appState?.catchError(ex);
}
/// The BuildContext for the App's View.
static BuildContext? get context => _appState?.lastContext;
/// The Scaffold object for this App's View.
static ScaffoldState get scaffold => Scaffold.of(context!);
// 'maybeOf' only in Beta channel
// static ScaffoldState get scaffold => Scaffold.maybeOf(context);
/// The Physical width of the screen
static double get screenPhysicalWidth {
final media = MediaQuery.of(context!);
return media.size.width * media.devicePixelRatio;
}
/// The logical width of the screen
static double get screenWidth => MediaQuery.of(context!).size.width;
/// The Physical height of the screen
static double get screenPhysicalHeight => MediaQuery.of(context!).size.height;
/// The Logical height of the screen
static double get screenHeight {
final media = MediaQuery.of(context!);
return media.size.height -
media.padding.top -
kToolbarHeight -
kBottomNavigationBarHeight;
}
// /// Current Screen Size
// static Size get screenSize {
// Size? size;
// final _context = context;
// if (_context == null) {
// size = MediaQueryData.fromWindow(mainWindow).size;
// } else {
// size = MediaQuery.of(_context).size;
// }
// return size;
// }
/// Current Screen Size
static Size get screenSize => MediaQueryData.fromWindow(mainWindow).size;
/// Set whether the app is to use a 'small screen' or not.
/// Determine if running on a desktop or on a phone or tablet
static bool get asSmallScreen => App.inDebugger && false;
/// Return the bool value indicating if running in a small screen or not.
static bool get inSmallScreen {
bool smallScreen;
// May be manually assigned.
smallScreen = asSmallScreen;
if (!smallScreen) {
smallScreen = screenSize.width < 800;
}
return smallScreen;
}
/// Determine the connectivity.
static final Connectivity _connectivity = Connectivity();
static StreamSubscription<ConnectivityResult>? _connectivitySubscription;
/// The local directory for this App.
static String? get filesDir => _path;
static String? _path;
/// Returns the connection status of the device.
static String? get connectivity => _connectivityStatus;
static String? _connectivityStatus;
/// Indicates if the app has access to the Internet.
static bool get isOnline => _connectivityStatus != 'none';
/// Connectivity listeners.
static final Set<ConnectivityListener> _listeners = {};
/// Add a Connectivity listener.
static bool addConnectivityListener(ConnectivityListener? listener) {
var add = false;
if (listener != null) {
add = _listeners.add(listener);
}
return add;
}
/// Remove a Connectivity listener.
static bool removeConnectivityListener(ConnectivityListener? listener) {
var remove = false;
if (listener != null) {
remove = _listeners.remove(listener);
}
return remove;
}
/// Clear Connectivity listeners.
static void clearConnectivityListener() => _listeners.clear();
/// The id for this App's particular installation.
static Future<String?> getInstallNum() => InstallFile.id();
/// The id for this App's particular installation.
static String? get installNum => _installNum;
static String? _installNum;
/// Internal Initialization routines.
Future<void> initInternal() async {
//
_connectivitySubscription ??=
_connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
for (final listener in _listeners) {
listener.onConnectivityChanged(result);
}
});
await _initConnectivity().then((status) {
_connectivityStatus = status;
}).catchError((e) {
_connectivityStatus = 'none';
});
// If running on the web the rest of the code is incompatible.
if (kIsWeb) {
return;
}
// Get the installation number
_installNum ??= await InstallFile.id();
// Determine the location to the files directory.
_path ??= await Files.localPath;
}
static Future<String> _initConnectivity() async {
String connectionStatus;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
connectionStatus = (await _connectivity.checkConnectivity()).toString();
} catch (ex) {
connectionStatus = 'Failed to get connectivity.';
}
return connectionStatus;
}
}
/// A Listener for the device's own connectivity status at any point in time.
mixin ConnectivityListener {
/// A listener method to respond if the device's connectivity changes.
void onConnectivityChanged(ConnectivityResult result);
}
/// Supply an MVC State object that hooks into the App class.
abstract class StateMVC<T extends StatefulWidget> extends mvc.StateMVC<T>
with HandleError {
/// Optionally supply a State Controller to be linked to this 'State' object.
StateMVC([ControllerMVC? controller]) : super(controller);
@override
void refresh() {
// Critical to have the App 'refresh' first.
// It uses a built-in InheritedWidget.
App.refresh();
if (mounted) {
// Next refresh the current State object itself.
super.refresh();
}
}
}
/// A standard Drawer object for your Flutter app.
class AppDrawer extends StatelessWidget {
/// Supply the properties to a Material Design [Drawer] Widget.
AppDrawer({
Key? key,
this.backgroundColor,
this.elevation,
this.shape,
this.semanticLabel,
this.header,
this.items,
}) : super(key: key) {
// Take any defined items.
if (items != null) {
_items.addAll(items!);
}
}
/// The drawer's color.
final Color? backgroundColor;
/// The z-coordinate at which to place this drawer relative to its parent.
final double? elevation;
/// The shape of the drawer.
final ShapeBorder? shape;
/// The semantic label of the dialog used by accessibility frameworks.
final String? semanticLabel;
/// The top-most region of a material design drawer.
final DrawerHeader? header;
/// The List of Widget items that make up the Drawer's contents.
final List<ListTile>? items;
final List<ListTile> _items = [];
/// one item
void add(ListTile? item) {
if (item != null) {
_items.add(item);
}
}
/// Add a List
void addAll(List<ListTile>? items) {
if (items != null) {
_items.addAll(items);
}
}
/// Remove an item
bool remove(ListTile? item) {
bool remove = item != null;
if (remove) {
remove = _items.remove(item);
}
return remove;
}
@override
Widget build(BuildContext context) {
final widgets = <Widget>[];
if (header != null) {
widgets.add(header!);
}
if (_items.isNotEmpty) {
widgets.addAll(_items);
}
return Drawer(
elevation: elevation ?? 16,
semanticLabel: semanticLabel,
child: ListView(
children: widgets,
));
}
}