Flutter Internationalization without BuildContext
Flutter Programming- August 9, 2023
- August 11, 2023
- Permalink
Internationalization is an important aspect of any application, it allows users to view an application in their preferred language and has been proven to increase user engagement.
Flutter offers several ways to internationalize your application, with Flutter recommending the Flutter_localizations package.
This method is very powerful and offers many useful features, but falls short when trying to internationalize classes and functions that do not have access to the build context.
There are several ways to deal with the lack of context, from using the Flutter Intl plugin, to countless StackOverflow answers on this topic or even switching to the Easy_localization plugin. But all (except the plugin method) require you to invest some time to get them to work properly.
That got me thinking, isn’t there an easier way to do this? Several days later, an idea popped up in my head:
Global Context
There are several ways to achieve this. We somehow need a way to access a build context which has access to the current locale.
My first idea was to create a global variable above my main function, called buildContext. The easiest method I could find was using the build method provided by the MaterialApp’s onGenerateTitle function.
Here’s how this would work, in your main.dart file, you’d have something like the following:
BuildContext? buildContext;
void main() {
...
}
class MyApp extends StatelessWidget {
...
Widget build(BuildContext context) {
...
return MaterialApp(
...,
onGenerateTitle: (context) {
buildContext = context;
return 'Your app title';
}
);
}
}
That’s it! We now have access to the build context globally. To simplify your translations, you can create a tr() function like so:
AppLocalizations tr() {
return AppLocalizations.of(buildContext!)!;
}
You can now start localizing anywhere in your app:
final myTranslation = tr().your_translation_key;
This method might have limitations or may not be considered best practices per SE, but it gets the job done, at least for me. Don’t hesitate to leave a comment below if you have any comments or tricks on Flutter Internationalization!
Christopher Al Khawand
I’m a university student currently living in France, in my 4th engineering year at Sorbonne University.
Passionate about programming, solving complex IT problems as well as new technological progress, learning new skills never stops.