1

I'm using flutter_localizations to internationalize my app. So i have this class

final Article article;
ArticleViewModel({required this.article});

String get name {
 return article.name;
}

String get isGood {
 return article.isGoods ? 'Goods' : 'Services';
}
}

Inside the isGood getter, i need to return "Goods" or "Services" translated depending on the language but i don't have the context to call Applocalization.of(context) I need a good approach to achieve this wihthout passing a BuildContext as parameter.

Xavier Soh
  • 47
  • 5

2 Answers2

2

You can try my approach, I have used this way for many of my apps. My way is inject BuildContext to a singleton class with get_it, like this:

@singleton
class AppContext {
  final navigatorKey = GlobalKey<NavigatorState>();

  BuildContext get navigatorContext => navigatorKey.currentState!.context;
}

then at your first time your app run, put the injected navigatorKey to MaterialApp:

MaterialApp(
  navigatorKey: getIt<AppContext>().navigatorKey,
)

Then, you can get BuildContext after that everywhere with:

getIt<AppContext>().navigatorContext
manhtuan21
  • 2,388
  • 2
  • 10
  • 24
  • Works fine! But where does the @singleton decorator comes from? I did withour it, and i had to register with ```getIt.registerSingleton(AppContext());``` inside the main before runApp(); – Xavier Soh Oct 17 '22 at 12:02
  • 1
    Aw yes, I forgot @singleton is the part of https://pub.dev/packages/injectable, which is code generator for get_it. You can register by yourself like you say but if you too lazy like me, you can use injectable xD – manhtuan21 Oct 17 '22 at 13:28
1

You could pass a BuildContext to your ViewModel (like you did with article) and call Applocalization.of(context) inside your getter

Ozan Taskiran
  • 2,922
  • 1
  • 13
  • 23