Getting BuildContext in Flutter for localization

后端 未结 4 1911
名媛妹妹
名媛妹妹 2021-02-13 17:00

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 somewh

4条回答
  •  渐次进展
    2021-02-13 17:47

    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 load(Locale locale) async {
        await initializeMessages(locale.toString());
        final result = Strings._(locale);
        return result;
      }
    
      static Strings of(BuildContext context) {
        return Localizations.of(context, Strings);
      }
    
      String get title {
        return Intl.message(
          'Hello World',
          name: 'title',
          desc: 'Title for the Demo application',
        );
      }
    }
    
    Future 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;
    

提交回复
热议问题