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.
CodePudding user response:
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
CodePudding user response:
You could pass a BuildContext to your ViewModel (like you did with article) and call Applocalization.of(context) inside your getter