init static method

Future<void> init({
  1. required AssetLoaderBase assetLoader,
  2. List<AssetLoaderBase>? assetLoadersExtra,
  3. List<Locale>? supportedLocales,
  4. List<String>? supportedLanguageCodes,
  5. LocalizationDefaultType defaultType = LocalizationDefaultType.device,
  6. String? hivePath,
  7. HiveStorageBackendPreference? hiveBackendPreference,
  8. JsonMapperBase? mapper,
})

Ensures that the package is initialized.


Implementation

static Future<void> init({
  required AssetLoaderBase assetLoader,
  List<AssetLoaderBase>? assetLoadersExtra,
  List<Locale>? supportedLocales,
  List<String>? supportedLanguageCodes,
  LocalizationDefaultType defaultType = LocalizationDefaultType.device,
  String? hivePath,
  HiveStorageBackendPreference? hiveBackendPreference,
  JsonMapperBase? mapper,
}) async {
  if (hivePath != null && hiveBackendPreference != null) {
    Hive.init(hivePath, backendPreference: hiveBackendPreference);
  } else if (hivePath != null && hiveBackendPreference == null) {
    Hive.init(hivePath);
  } else {
    await Hive.initFlutter();
  }

  await DBBox.openBox();

  await _writeSettings(
    supportedLocales: supportedLocales,
    supportedLanguageCodes: supportedLanguageCodes,
    type: defaultType,
  );

  Map<String, dynamic> primaryTranslations = <String, dynamic>{};
  Map<String, dynamic> fallbackTranslations = <String, dynamic>{};
  Map<String, dynamic> finalTranslations = <String, dynamic>{};

  try {
    // Attempt to load translations using the primary asset loader
    primaryTranslations = await assetLoader.load(mapper);
    debugPrint('--LocalizeAndTranslate-- Primary asset loader succeeded');
  } catch (e) {
    debugPrint('--LocalizeAndTranslate-- Primary asset loader failed: $e');
  }

  if (assetLoadersExtra != null) {
    for (final AssetLoaderBase loader in assetLoadersExtra) {
      try {
        // Attempt to load translations using the secondary asset loader
        final Map<String, dynamic> secondaryTranslations = await loader.load(mapper);
        debugPrint('--LocalizeAndTranslate-- Secondary asset loader succeeded');
        fallbackTranslations = secondaryTranslations;
        break;
      } catch (e) {
        debugPrint('--LocalizeAndTranslate-- Secondary asset loader failed: $e');
      }
    }
  }

  // Merge primary and fallback translations
  finalTranslations = <String, dynamic>{...fallbackTranslations, ...primaryTranslations};

  await _writeTranslations(data: finalTranslations);

  debugPrint(
    '--LocalizeAndTranslate-- init | LanguageCode: ${getLanguageCode()}'
    ' | CountryCode: ${getCountryCode()} | isRTL: ${isRTL()}',
  );
}