flutterfirebasegoogle-cloud-firestorefirebase-remote-configflutter-localizations

Flutter localization using Firebase Remote Config


I want to create a Flutter app that will support different languages based on user device localization.

I want to store all translation texts via Firebase Remote Config. That way, remote changes will apply to all users without the need to update the app.

Right now, my app works with localizations based on the official documentation. But that way all texts are hard-coded, so users will have to update the app in order to get new text changes.

My research

I have read a post about creating a custom LocalizationsDelegate, maybe that way I could load all texts from Firebase and on run-time.

I have also read about the easy_localization package, but unfuruentally it seems to support hard-coded texts only out of the box.

Question

What is the best approach to achieve dynamic localizations within Firebase configuration?

I would appreciate an example 🙏


Solution

  • Problem Solved!

    You can use the easy_localization package and create a custom AssetLoader that supports Firebase Remote Config assets.

    I have created JSON parameters for each supported language on my Firebase Remote Config project.

    enter image description here

    Then I created a RemoteConfigAssetLoader class that extends the easy_localiztion's AssetLoader class:

    import 'dart:convert';
    import 'dart:ui';
    
    import 'package:easy_localization/easy_localization.dart';
    import 'package:firebase_remote_config/firebase_remote_config.dart';
    import 'package:get_it/get_it.dart';
    
    final _remoteConfig = GetIt.I.get<FirebaseRemoteConfig>(); // A remoteConfig instance. You can get it also as a class parameter.
    
    /// Loads [FirebaseRemoteConfig] translations based on users' device local.
    class RemoteConfigAssetLoader extends AssetLoader {
      @override
      Future<Map<String, dynamic>> load(String path, Locale locale) async {
        final remoteConfigKey = locale.languageCode;    
        final languageData = _remoteConfig.getString(remoteConfigKey);
        return jsonDecode(languageData) as Map<String, dynamic>;
      }
    }
    

    Then just configure your app EasyLocalization with your custom RemoteConfigAssetLoader function:

    import 'util/remote_config_asset_loader.dart';
      ...
      void main(){
        runApp(EasyLocalization(
          child: MyApp(),
          supportedLocales: [Locale('en'), Locale('es')],
          path: 'IgnoreThisPath', // The path parameter is unnecessary when using the RemoteConfig singleton.
          assetLoader: RemoteConfigAssetLoader()
        ));
      }
      ...
    

    That's it! Now your EasyLocalization loads its translations from your Firebase RemoteConfig.