Getting BuildContext in Flutter for localization. You don’t need BuildContext to access strings. Here is my solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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:
1 | final title = Strings.current.title; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.