-
Notifications
You must be signed in to change notification settings - Fork 0
/
var.dart
68 lines (55 loc) · 2.11 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
import 'package:flutter/widgets.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_mediator_lite/mediator.dart';
import 'package:shared_preferences/shared_preferences.dart';
//* Declare a global scope SharedPreferences.
late SharedPreferences prefs;
//* Step1A: Declare the watched variable with `globalWatch`.
final touchCount = globalWatch(0, tag: 'tagCount'); // main.dart
final data = globalWatch(<ListItem>[]); // list_page.dart
//* Step1B: Declare the persistent watched variable with `late Rx<Type>`
const DefaultLocale = 'en';
late Rx<String> locale; // local_page.dart
final opacityValue = globalWatch(0.0); // scroll_page.dart
class ListItem {
const ListItem(
this.item,
this.units,
this.color,
);
final String item;
final int units;
final Color color;
}
/// Initialize the persistent watched variables
/// whose value is stored by the SharedPreferences.
Future<void> initVars() async {
// To make sure SharedPreferences works.
WidgetsFlutterBinding.ensureInitialized();
prefs = await SharedPreferences.getInstance();
locale = globalWatch(prefs.getString('locale') ?? DefaultLocale);
}
/// Change the locale, by `String`[countryCode]
/// and store the setting with SharedPreferences.
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.
locale.value = countryCode; // will rebuild the registered widget
await prefs.setString('locale', countryCode);
}
}
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),
);
}
}