ilteoood / flutter_i18n

I18n made easy, for Flutter!
MIT License
217 stars 57 forks source link

Fix TypeError in calculateSubmap #197

Closed adrianFarkas closed 2 years ago

adrianFarkas commented 2 years ago

The Problem

I wanted to upgrade versions in an old template project of my company which uses flutter_i18n for the translations and i ran into this error:

type 'String' is not a subtype of type 'Map<dynamic, dynamic>?'

When the exception was thrown, this was the stack:
#0      SimpleTranslator.calculateSubmap.<anonymous closure> (package:flutter_i18n/utils/simple_translator.dart:60:49)
#1      List.forEach (dart:core-patch/growable_array.dart:416:8)
#2      SimpleTranslator.calculateSubmap (package:flutter_i18n/utils/simple_translator.dart:60:28)
#3      SimpleTranslator._decodeFromMap (package:flutter_i18n/utils/simple_translator.dart:45:42)

Based on the stack, i started to search for the problem in the SimpleTranslator and i found out that the problem was that we had two locale files which were different:

// en.json
{
 "fields": {
    "email": {
      "label": "Your email address",
      "mandatory_error": "Please enter your email",
      "invalid_email": "Please enter a valid email address",
      "email_taken": "This email address is already registered."
  }
  ...
}

// hu.json
{
 "fields": {
    "email": "Email cím",
    ...
}

And we used the fields.email.label key everywhere but it looks like we forgot to check if everything works with the other language too since it's just a template project. So the problem is that the calculateSubmap's return type is Map<dynamic, dynamic> but the value of the key for the other language is not a Map but a String which causes this error.

It looks a minor problem that can be fixed by adding the proper translations to the json files but if somebody forget it then the error message is not really useful to find the problem. So now it checks if the value is a Map or not and it will gives back an empty Map is it's not. By this, it will just call the missingKeyTranslationHandler and shows the key that you passed.

ilteoood commented 2 years ago

Tysm for your contribution man, really appreciated.

To check the correctness of your translation file, I suggest to use this library: it is able to do it.

ilteoood commented 2 years ago

Published with version 0.32.3