Flutter localisation not working when adding a new language

341 Views Asked by At

I'm trying to write my simple flutter app for adding localisation for new language name "Hmong" with language code "hmn".

I've written some file of code there as described in docs. But, not working for me,

main.dart file code,

localizationsDelegates:  [
                  Translations.delegate,
                  TranslationsHMNDelegate (),
                  GlobalMaterialLocalizations.delegate,
                  GlobalWidgetsLocalizations.delegate,
                  GlobalCupertinoLocalizations.delegate,
                ],
                locale: value.appLocale,
                supportedLocales: [Locale('en'), Locale('hmn')],

Delegate file code,

class TranslationsHMNDelegate extends LocalizationsDelegate<Translations> {
  @override
  bool isSupported(Locale locale) {
    return locale.languageCode == "hmn";
  }

  @override
  Future<Translations> load(Locale locale) async {
    return HmnTranslations ();
  }

  @override
  bool shouldReload(dynamic old) {
    return false;
  }
}

class HmnTranslations extends Translations{
  // added hmn translations with 137 overridden methods here
}

Translations file code,

    class Translations {
      const Translations();
      static Translations? current;
      static Translations? of(BuildContext context) {
        return Localizations.of<Translations>(context, Translations);
      }
    
      static const LocalizationsDelegate<Translations> delegate =
          _TranslationsDelegate();

      // Other english translations added here.
    }

    class _TranslationsDelegate extends LocalizationsDelegate<Translations> {
  const _TranslationsDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['en', 'hmn'].contains(locale.languageCode);
  }

  @override
  Future<Translations> load(Locale locale) async {
    if (locale.languageCode.toLowerCase() == 'hmn') {
      Translations.current = HmnTranslations();
      return SynchronousFuture<Translations>(
          Translations.current ?? const Translations());
    }
    Translations.current = const Translations();
    return SynchronousFuture<Translations>(
        Translations.current ?? const Translations());
  }

  @override
  bool shouldReload(_TranslationsDelegate old) => false;
}

But, this is not working for me. I'm getting errors like following,

======== Exception caught by widgets ===============================================================
The following message was thrown:
This application's locale, hmn, is not supported by all of its localization delegates.

• A MaterialLocalizations delegate that supports the hmn locale was not found.
• A CupertinoLocalizations delegate that supports the hmn locale was not found.

The declared supported locales for this app are: en, hmn

So can anyone please help me with this? Thank you.

0

There are 0 best solutions below