/
var.dart
79 lines (67 loc) · 2.47 KB
/
var.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
import 'package:flutter/widgets.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_mediator_persistence/mediator.dart';
//* Login token from the REST server.
var loginToken = '';
const DefaultLocale = 'en';
//* Declare a persistent watched variable with `defaultVal.globalPersist('key')`
/// int: 0.globalPersist('intKey');
/// double: 0.0.globalPersist('doubleKey');
/// String: ''.globalPersist('StringKey');
/// bool: false.globalPersist('boolKey');
final locale = DefaultLocale.globalPersist('locale');
final themeIdx = 1.globalPersist('themeIdx');
//* Declare the watched variable with `globalWatch(initialValue)`.
final touchCount = globalWatch(0, tag: 'tagCount'); // main.dart
final data = globalWatch(<ListItem>[]); // list_page.dart
class ListItem {
const ListItem(
this.item,
this.units,
this.color,
);
final String item;
final int units;
final Color color;
}
/// Change the locale, by `String`[countryCode]
Future<void> changeLocale(BuildContext context, String countryCode) async {
if (countryCode != locale.value) {
final loc = Locale(countryCode);
await FlutterI18n.refresh(context, loc);
//* Step4: Make an update to the watched variable.
//* The persistent watched variable will update the persistent value automatically.
locale.value = countryCode; // will rebuild the registered widget
}
}
/// Change the theme, by ThememData `int` [idx]
void changeTheme(int idx) {
idx = idx.clamp(0, 1);
if (idx != themeIdx.value) {
themeIdx.value = idx; // will rebuild the registered widget
}
}
/// Sign out from the REST server and clear the [loginToken].
void onSignOut(BuildContext context) {
loginToken = '';
Navigator.of(context).pushReplacementNamed('/');
}
extension StringI18n on String {
/// String extension for i18n.
String i18n(BuildContext context) {
return FlutterI18n.translate(context, this);
}
/// String extension for i18n and `locale.consume` the widget
/// to create consume widget for the state management.
Widget ci18n(BuildContext context, {TextStyle? style}) {
return locale.consume(
() => Text(FlutterI18n.translate(context, this), style: style),
);
}
}
/// Get the screen width
double getScreenWidth(BuildContext context) =>
MediaQuery.of(context).size.width;
/// Get the screen height
double getScreenHeight(BuildContext context) =>
MediaQuery.of(context).size.height;