-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathapp_localizations.dart
60 lines (46 loc) · 2 KB
/
app_localizations.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
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class AppLocalizations {
static const LocalizationsDelegate<AppLocalizations> delegate =
_AppLocalizationsDelegate();
final Locale locale;
// Helper method to keep the code in the widgets concise
// Localizations are accessed using an InheritedWidget "of" syntax
Map<String, String> _localizedStrings;
// Static member to have a simple access to the delegate from the MaterialApp
AppLocalizations(this.locale);
Future load() async {
// Load the language JSON file from the "lang" folder
String jsonString = await rootBundle.loadString("assets/lang/lang.json");
Map<String, dynamic> jsonMap = json.decode(jsonString);
_localizedStrings = jsonMap.map((String key, dynamic value) {
return MapEntry(key, value["${locale.languageCode}"].toString());
});
}
String translate(String key) => _localizedStrings[key];
// This method will be called from every widget which needs a localized text
static AppLocalizations of(BuildContext context) =>
Localizations.of<AppLocalizations>(context, AppLocalizations);
}
// LocalizationsDelegate is a factory for a set of localized resources
// In this case, the localized strings will be gotten in an AppLocalizations object
class _AppLocalizationsDelegate
extends LocalizationsDelegate<AppLocalizations> {
// This delegate instance will never change (it doesn't even have fields!)
// It can provide a constant constructor.
static const List<String> _supportedLocales = ["en", "it", "pt","de"];
const _AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) =>
_supportedLocales.contains(locale.languageCode);
@override
Future<AppLocalizations> load(Locale locale) async {
AppLocalizations localizations = AppLocalizations(locale);
await localizations.load();
return localizations;
}
@override
bool shouldReload(_AppLocalizationsDelegate old) => false;
}