I try to localize a String in Flutter with the localization package. The problem is the location where my translation is needed. It is not related to the UI, rather it is somewhere deep in my model, where I don't have access to a BuildContext. Is there any other possibility to still make use of the translation function?
// I don't have a context variable here
MyLocalizations.of(context).trans("foo")
BuildContext is a locator that is used to track each widget in a tree and locate them and their position in the tree. The BuildContext of each widget is passed to their build method. Remember that the build method returns the widget tree a widget renders. Each BuildContext is unique to a widget.
Just click on Tools > Flutter Intl > Add Locale. This will open a popup where you can write the name of the . arb file for the particular language. Let's add support for the Hindi language, so enter.
By default, Flutter only provides US English localizations. To add support for other languages, an application must specify additional MaterialApp (or CupertinoApp ) properties, and include a package called flutter_localizations . As of November 2020, this package supports 78 languages.
Yes there is. You don't need BuildContext to access strings. Here is my solution:
class Strings {
Strings._(Locale locale) : _localeName = locale.toString() {
current = this;
}
final String _localeName;
static Strings current;
static Future<Strings> load(Locale locale) async {
await initializeMessages(locale.toString());
final result = Strings._(locale);
return result;
}
static Strings of(BuildContext context) {
return Localizations.of<Strings>(context, Strings);
}
String get title {
return Intl.message(
'Hello World',
name: 'title',
desc: 'Title for the Demo application',
);
}
}
Future<Null> main() async {
final Locale myLocale = Locale(window.locale);
await Strings.load(myLocale);
runApp(MyApplication());
}
Now you can reference a string as follows:
final title = Strings.current.title;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With