flutter _i18n 國際化

添加依賴

將其添加到包的pubspec.yaml文件中:

dependencies: flutter_i18n: ^0.6.3json

建立json翻譯文件

建立兩個或者多個文件,

/assets/i18n/en.jsonbash

"title": "Test",
  "label": {
    "main": "Hello {user}!"
  },
  "button": {
    "clickMe": "Click here"
  },
  "toastMessage": "You clicked on button!",
  "clicked": {
    "times-0": "You clicked {times} times!",
    "times-1": "You clicked {time} time!",
    "times-2": "You clicked {times} times!"
  }
}
複製代碼

/assets/i18n/zh.jsonasync

{
  "title": "測試",
  "label": {
    "main": "您好 {user}!"
  },
  "button": {
    "clickMe": "Premi qui"
  },
  "toastMessage": "Hai premuto un bottone!",
  "clicked": {
    "times-0": "Hai premuto {times} volte!",
    "times-1": "Hai premuto {time} volta!",
    "times-2": "Hai premuto {times} volte!"
  }
}
複製代碼

在pubspec.yaml文件中添加資源配置:

flutter:
  uses-material-design: true
  assets:
   - assets/i18n/
複製代碼

入口文件 主要代碼

localizationsDelegates: [
        // 本地化的代理類
        FlutterI18nDelegate(useCountryCode: false, fallbackFile: 'zh', path: 'assets/i18n'),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
   ],
   supportedLocales: [
        const Locale('en', 'US'), // 美國英語
        const Locale('zh', 'CN'), // 中文簡體
        //其它Locales
    ],
複製代碼

頁面使用

Locale currentLang;
  int clicked = 8;
  @override
  void initState() { 
    super.initState();
    new Future.delayed(Duration.zero, () async {
      await FlutterI18n.refresh(context, new Locale('en'));//這裏主要設置引入語言包
      setState(() {
        currentLang = FlutterI18n.currentLocale(context);
      });
    });
  }
複製代碼

Text(FlutterI18n.translate(context, "title")),ide

改變語言

setState(() {
    currentLang.languageCode=='en' ?  FlutterI18n.refresh(context, new Locale('zh')) : FlutterI18n.refresh(context, new Locale('en'));
  });
複製代碼
相關文章
相關標籤/搜索