I have a localized Android Flutter app. I configured localization following these instructions. This works (although it feels unnecessarily complicated), and I am able to use localized strings throughout the app, but I cannot figure out how to load a localized asset JSON file.
I tried to store asset path as a localized string. But when I try to load the path from statefull widget's initState
I get an error.
@override
void initState() {
var t = AppLocalizations.of(context);
await rootBundle.load(t!.localizedJsonPath);
super.initState();
}
FlutterError (dependOnInheritedWidgetOfExactType<_LocalizationsScope>() or dependOnInheritedElement() was called before _MyScreenState.initState() completed.
Note that above approach works fine if I hard code the JSON asset file path. It only fails when I try to load the localized string.
What am I doing wrong?
If there is a better way to load localized assets I will accept that as an answer. Flutter documentation mentions asset variants for image resolution and themes, but I could not find anything for localization.
CodePudding user response:
The error you are getting appears to be with your context.
var t = AppLocalizations.of(context);
is called inside initState. However, your init state is called before your widget has a context, because it didn't build yet. So what you can try to do is use didChangeDependencies()
instead of initState, like that:
@override
void didChangeDependencies() {
var t = AppLocalizations.of(context);
await rootBundle.load(t!.localizedJsonPath);
super.didChangeDependencies();
}
and one more thing: init state is not async, so try toawait
the methods you call does not really work.
keep me updated if your problem still persist!