Getting BuildContext in Flutter for localization

后端 未结 4 1904
名媛妹妹
名媛妹妹 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:33

    I know this question is dated way back. But I came across this issue when implementing my application, and I dont see any "nice" way to handle it. So here is my approach

    class LanguageService {
      static String defaultLanguage = 'en';
    
      static Map> _localizedValues = {
        'en': {
          'title': 'Storefront',
          'language': 'Language',
          'googleLogin': 'Login with Google'
        },
        'vn': {
          'title': 'Cửa hàng',
          'language': 'Ngôn ngữ',
          'googleLogin': 'Đăng Nhập với Google'
        }
      };
    
      static set language(String lang) {
        defaultLanguage = lang;
      }
    
      static String get title {
        return _localizedValues[defaultLanguage]['title'];
      }
    
      static String get language {
        return _localizedValues[defaultLanguage]['language'];
      }
    
      static String get googleLogin {
        return _localizedValues[defaultLanguage]['googleLogin'];
      }
    
    }
    

    Now you can reference a string as follows:

    String title = LanguageService.title;
    

    You can find the detailed tutorial here

提交回复
热议问题