There is a library called easy_localization that does localization without context, you can simply use that one. Library also provides more convenient approach of writing less code and still localizing all the segments of the app. An example main class:
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]).then((_) {
runApp(EasyLocalization(
child: MyApp(),
useOnlyLangCode: true,
startLocale: Locale('nl'),
fallbackLocale: Locale('nl'),
supportedLocales: [
Locale('nl'),
Locale('en'),
],
path: 'lang',
));
});
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SplashScreen(),
supportedLocales: EasyLocalization.of(context).supportedLocales,
locale: EasyLocalization.of(context).locale,
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
DefaultCupertinoLocalizations.delegate,
EasyLocalization.of(context).delegate,
],
localeResolutionCallback: (locale, supportedLocales) {
if (locale == null) {
EasyLocalization.of(context).locale = supportedLocales.first;
Intl.defaultLocale = '${supportedLocales.first}';
return supportedLocales.first;
}
for (Locale supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode) {
EasyLocalization.of(context).locale = supportedLocale;
Intl.defaultLocale = '$supportedLocale';
return supportedLocale;
}
}
EasyLocalization.of(context).locale = supportedLocales.first;
Intl.defaultLocale = '${supportedLocales.first}';
return supportedLocales.first;
},
);
}
}
Also don't forget to put localization path to your pubspec.yamal
file!
After all of this is done, you can simply just use it in a Text
widget like this:
Text(tr('someJsonKey'),),