Advertisement
Guest User

app_localization

a guest
Jan 23rd, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1.  
  2.  
  3. ```
  4. import 'dart:async';
  5. import 'dart:convert';
  6.  
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter/services.dart';
  9.  
  10. class AppLocalizations {
  11. final Locale locale;
  12. AppLocalizations(this.locale);
  13. // Static member to have a simple access to the delegate from the MaterialApp
  14. static AppLocalizations of(BuildContext context) {
  15. return Localizations.of<AppLocalizations>(context, AppLocalizations);
  16. }
  17.  
  18. static const LocalizationsDelegate<AppLocalizations> delegate =
  19. _AppLocalizationsDelegate();
  20.  
  21. Map<String, String> _localizedStrings;
  22.  
  23. Future<bool> load() async {
  24. // Load the language JSON file from the "lang" folder
  25. String jsonString =
  26. await rootBundle.loadString('lang/${locale.languageCode}.json');
  27. Map<String, dynamic> jsonMap = json.decode(jsonString);
  28. print(locale);
  29. _localizedStrings = jsonMap.map((key, value) {
  30. return MapEntry(key, value.toString());
  31. });
  32.  
  33. return true;
  34. }
  35.  
  36.  
  37. // This method will be called from every widget which needs a localized text
  38. String translate(String key) {
  39. return _localizedStrings[key];
  40. }
  41. }
  42.  
  43. // LocalizationsDelegate is a factory for a set of localized resources
  44. // In this case, the localized strings will be gotten in an AppLocalizations object
  45. class _AppLocalizationsDelegate
  46. extends LocalizationsDelegate<AppLocalizations> {
  47. // This delegate instance will never change (it doesn't even have fields!)
  48. // It can provide a constant constructor.
  49. const _AppLocalizationsDelegate();
  50.  
  51. @override
  52. bool isSupported(Locale locale) {
  53. // Include all of your supported language codes here
  54. return ['en', 'ar'].contains(locale.languageCode);
  55. }
  56.  
  57. @override
  58. Future<AppLocalizations> load(Locale locale) async {
  59. // AppLocalizations class is where the JSON loading actually runs
  60. AppLocalizations localizations = new AppLocalizations(locale);
  61. await localizations.load();
  62. return localizations;
  63. }
  64.  
  65. @override
  66. bool shouldReload(_AppLocalizationsDelegate old) => false;
  67. }
  68. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement