String xml file in Flutter

后端 未结 7 1883
难免孤独
难免孤独 2021-02-01 15:18

In flutter string text are directly set to the TextField widget like:

new Text(\'Hello,  How are you?\')

Is correct way ? or we ca

7条回答
  •  时光说笑
    2021-02-01 15:31

    For those of you who don't want to use any 3rd party plugin, here is how you can do it.

    1. Create a folder strings in assets. Put your language file in it.

      assets
        strings
        - en.json // for english 
        - ru.json  // for russian
      
    2. Now in en.json, write your string, for example.

      {
        "text1": "Hello",
        "text2": "World"
      }
      

      Similarly, in ru.json,

      {
        "text1": "Привет",
        "text2": "Мир"
      }
      
    3. Add this to pubspec.yaml file (mind the spaces)

      flutter:
      
        uses-material-design: true
      
        assets:
          - assets/strings/en.json
          - assets/strings/ru.json
      
    4. Now you are all set to use these strings in your app. Here is the sample code, the AppBar shows the translated text.

      void main() {
        runApp(
          MaterialApp(
            locale: Locale("ru"), // switch between en and ru to see effect
            localizationsDelegates: [const DemoLocalizationsDelegate()],
            supportedLocales: [const Locale('en', ''), const Locale('ru', '')],
            home: HomePage(),
          ),
        );
      }
      
      class HomePage extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            appBar: AppBar(title: Text(DemoLocalizations.of(context).getText("text2") ?? "Error")),
          );
        }
      }
      
      // this class is used for localizations
      class DemoLocalizations {
        static DemoLocalizations of(BuildContext context) {
          return Localizations.of(context, DemoLocalizations);
        }
      
        String getText(String key) => language[key];
      }
      
      Map language;
      
      class DemoLocalizationsDelegate extends LocalizationsDelegate {
        const DemoLocalizationsDelegate();
      
        @override
        bool isSupported(Locale locale) => ['en', 'ru'].contains(locale.languageCode);
      
        @override
        Future load(Locale locale) async {
          String string = await rootBundle.loadString("assets/strings/${locale.languageCode}.json");
          language = json.decode(string);
          return SynchronousFuture(DemoLocalizations());
        }
      
        @override
        bool shouldReload(DemoLocalizationsDelegate old) => false;
      }
      

提交回复
热议问题