ilteoood / flutter_i18n

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

Translate without context #188

Closed MilosKarakas closed 2 years ago

MilosKarakas commented 2 years ago

Hi, First of all thanks for an amazing package. I've been using it for a while and it's worked just great.

At work, I got a task which required me to assign a default name to a file, which had to be different depending on the user's language preferences. This is supposed to be done in the data layer, at least that's where we do it.

If we were to continue using FlutterI18n to do it, we would have to find a way to inject the BuildContext all the way down to the data layer, which would make a real mess in our codebase. So, I've decided to make a PR to enable getting an FlutterI18n instance without BuildContext. It's not completely ruled out, you still need it when registering the service, but that's about it.

We use get_it for dependency injection so we just register FlutterI18n at app start, and then fetch it wherever we need it, eg.

if (!injector.isRegistered<FlutterI18n>()) {
    injector.registerLazySingleton<FlutterI18n>(() => FlutterI18n.of(context));
  }

you retrieve it like this:

FlutterI18n instance = GetIt.instance.get();

and you can use it like this:

String translation = FlutterI18n.translateWithInstance(instance, key);

and that's about it.

translateWithInstance(..) is the method that's I've added to avoid making any breaking changes by editing the existing translate() method.

ilteoood commented 2 years ago

Hi @MilosKarakas, The idea is great but if we want this feature we should support also the other translators, not only the simple one.

BTW, tests are missing

MilosKarakas commented 2 years ago

@ilteoood I'll take a look later and adjust the PR. Will add tests too probably.

ilteoood commented 2 years ago

Hi @MilosKarakas, any news?

MilosKarakas commented 2 years ago

Hey @ilteoood I've been using the fork with just the part the I've added already. I had no time to complete the PR. Expect it in the next 2 weeks, for all translators, together with tests.

MilosKarakas commented 2 years ago

@ilteoood I have created another PR with an API that looks more logical to me. I have covered translators and widgets, together with tests. I am closing this PR.