Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```
- import 'dart:async';
- import 'dart:convert';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- class AppLocalizations {
- final Locale locale;
- AppLocalizations(this.locale);
- // Static member to have a simple access to the delegate from the MaterialApp
- static AppLocalizations of(BuildContext context) {
- return Localizations.of<AppLocalizations>(context, AppLocalizations);
- }
- static const LocalizationsDelegate<AppLocalizations> delegate =
- _AppLocalizationsDelegate();
- Map<String, String> _localizedStrings;
- Future<bool> load() async {
- // Load the language JSON file from the "lang" folder
- String jsonString =
- await rootBundle.loadString('lang/${locale.languageCode}.json');
- Map<String, dynamic> jsonMap = json.decode(jsonString);
- print(locale);
- _localizedStrings = jsonMap.map((key, value) {
- return MapEntry(key, value.toString());
- });
- return true;
- }
- // This method will be called from every widget which needs a localized text
- String translate(String key) {
- return _localizedStrings[key];
- }
- }
- // 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.
- const _AppLocalizationsDelegate();
- @override
- bool isSupported(Locale locale) {
- // Include all of your supported language codes here
- return ['en', 'ar'].contains(locale.languageCode);
- }
- @override
- Future<AppLocalizations> load(Locale locale) async {
- // AppLocalizations class is where the JSON loading actually runs
- AppLocalizations localizations = new AppLocalizations(locale);
- await localizations.load();
- return localizations;
- }
- @override
- bool shouldReload(_AppLocalizationsDelegate old) => false;
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement