Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

erro ao fazer guardar e buscar linguagem em cache

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final localization = LocalizationManager();

  await localization.loadLanguageCode();
  await localization.loadLanguageFile(localization.languageCode);
  runApp(ChangeNotifierProvider(
    create: (_) => localization,
    child: const Grimorio(),
  ));
}

class Grimorio extends StatelessWidget {
  const Grimorio({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Meu Pequeno Grimório",
      theme: ThemeData.dark(useMaterial3: true),
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en'),
        Locale('es'),
        Locale('pt', "BR"),
      ],
      home: const SplashScreen(),
    );
  }
}
class PrefsKeys {
  static const String language = "LANGUAGE";
  String languageFile(String languageCode) {
    return "LANGUAGE_FILE_$languageCode";
  }
}
class LocalizationManager extends ChangeNotifier {
  String languageCode = 'en';

  final Map<String, Map<String, String>> _mapLanguages = {
    "en": {},
    "pt": {},
    "es": {},
  };

  Future<void> _saveLanguageFile(String newCode) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(
      PrefsKeys().languageFile(newCode),
      json.encode(_mapLanguages[newCode]),
    );
  }

  Future<void> loadLanguageFile(String newCode) async {
    if (_mapLanguages[newCode] == null) {
    final prefs = await SharedPreferences.getInstance();
      String? result = prefs.getString(PrefsKeys().languageFile(newCode));
      if (result != null) {
        Map<String, dynamic> resultMap = json.decode(result);
        _mapLanguages[newCode] = resultMap.map(
          (key, value) {
            return MapEntry(key, value.toString());
          },
        );
      } else {
        await getLanguageFromServer(newCode);
      }
    }
  }

  String _getSentence(String keySentence) {
    String? sentence = _mapLanguages[languageCode]?[keySentence];
    sentence ??= _mapLanguages["en"]?[keySentence];
    return sentence!;
  }

  Future<void> setLanguage(String newCode) async {
    await loadLanguageFile(newCode);
    await _saveLanguageCode(newCode);
    languageCode = newCode;
    notifyListeners();
  }

  Future<void> _saveLanguageCode(String newCode) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(PrefsKeys.language, newCode);
  }

  Future<void> loadLanguageCode() async {
    final prefs = await SharedPreferences.getInstance();

    String? possibleLanguage = prefs.getString(PrefsKeys.language);

    if (possibleLanguage != null) {
      languageCode = possibleLanguage;
    } else {
      languageCode = 'en';
    }
    notifyListeners();
  }

  Future<void> getLanguageFromServer(String newCode) async {
    String url =
        "https://gist.githubusercontent.com/PedruHNS/e726aa31c060c4c3f75e679f316b741c/raw/bed2925cd6cd9bc7ba18b1a5cf88c89085b0c7a7/app_$newCode.json";

    final response = await http.get(Uri.parse(url));

    Map<String, dynamic> mapResponse = json.decode(response.body);

    _mapLanguages[newCode] = mapResponse.map(
      (key, value) => MapEntry(
        key,
        value.toString(),
      ),
    );

    _saveLanguageFile(newCode);
  }

  String get clearBooksText => _getSentence("clearBooksText");
  String get languageDialogText => _getSentence("languageText");
  String get clearDialogButtonText => _getSentence("clearButton");
  String get portugueseDropdownText => _getSentence("portugueseDropdownText");
  String get englishDropdownText => _getSentence("englishDropdownText");
  String get spanishDropdownText => _getSentence("spanishDropdownText");
  String get homeTitleText => _getSentence("homeTitle");
  String get homeEmptyText => _getSentence("homeEmpty");
  String get homeEmptyCallText => _getSentence("homeEmptyCall");

  String get deviceDefaultDropDownText =>
      _getSentence("defaultDeviceLanguageItem");
}

erro descrito no debug

1 resposta
solução!

descobri o problema, fui debugar o Localization_manager e raparei e ao verificar se o _mapLanguages era igual a null ele sempre caia fora, porque acabei esquecendo de remover os valores do map, quando retirei esses valores, funcionou