Локализация flutter приложения
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AppLocalizations {
final Locale locale;
AppLocalizations(this.locale);
// Helper method to keep the code in the widgets concise
// Localizations are accessed using an InheritedWidget "of" syntax
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
// Static member to have a simple access to the delegate from the MaterialApp
static const LocalizationsDelegate<AppLocalizations> delegate =
_AppLocalizationsDelegate();
Map<String, String> _localizedStrings;
Future<bool> load() async {
// Load the language JSON file from the "lang" folder
final String jsonString =
await rootBundle.loadString('i18n/${locale.languageCode}.json');
final jsonMap = json.decode(jsonString) as Map<String, dynamic>;
_localizedStrings = jsonMap.map((String 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];
}
}
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
// ignore: always_specify_types
return ['en', 'pl'].contains(locale.languageCode);
}
@override
Future<AppLocalizations> load(Locale locale) async {
final AppLocalizations localizations = AppLocalizations(locale);
await localizations.load();
return localizations;
}
@override
bool shouldReload(_AppLocalizationsDelegate old) => false;
}
class AppLanguage extends ChangeNotifier {
Locale _appLocale = const Locale('en');
Locale get appLocal => _appLocale ?? const Locale('en');
// ignore: prefer_void_to_null
Future<dynamic> fetchLocale() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getString('language_code') == null) {
_appLocale = const Locale('en');
return null;
}
_appLocale = Locale(prefs.getString('language_code'));
return null;
}
// ignore: avoid_void_async
void changeLanguage(Locale type) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (_appLocale == type) {
return;
}
if (type == const Locale('pl')) {
_appLocale = const Locale('pl');
await prefs.setString('language_code', 'pl');
await prefs.setString('countryCode', '');
}
else {
_appLocale = const Locale('en');
await prefs.setString('language_code', 'en');
await prefs.setString('countryCode', 'US');
}
notifyListeners();
}
}
Вот весь код из файла, ошибка где-то в классе AppLanguage
