Skip to content

Running context.setLocale doesn't reload the language from AssetLoader #768

@nemr0

Description

@nemr0

Hello There,

I made my own AssetLoader with an lazy loading feature,
So I have one source of truth which is a path in support directory, first time I open the app I save language assets to it,
I made it so After loading the file from APIs, I use a global key to get context to setLocale again so I can reload the current file.

is there any other way to do this or that's a problem with setLocale?

here's an example:

class AssetLoaderExample extends AssetLoader {
  final RemoteDatasource _remoteDatasource;
  AssetLoaderExample(this._remoteDatasource);
  @override
  Future<Map<String, dynamic>?> load(String path, Locale locale) async {
    _loadFromApi(path, locale);
    return getFromFile(path, locale);
  }
  void _loadFromApi(String path,Locale locale) async {
    final response = await _remoteDatasource.get(path: 'path/to/localization/${locale.languageCode}.json', withToken: false);
    if (response.isLeft()) return;
    final content = response.asRight.data;
    if (content.isEmpty || content == '{}' || content.contains('Access Denied')) {
      // Handle the case where the content is empty or invalid.
      return null;
    }
    File('$path/${locale.languageCode}').writeAsStringSync(content);
    final context = navigatorKey.currentContext;
    if (context != null && context.mounted) {
      context.setLocale(locale);
    }
  }
  
  getFromFile(String path, Locale locale){
    final file = File('$path/${locale.languageCode}.json');
    if (file.existsSync()) {
      final content = file.readAsStringSync();
      return jsonDecode(content);
    }
    return null;
  }
  
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions