Flutter國際化

Flutter國際化

preview.gif

集成easy_localization插件

flutter pub add easy_localization easy_logger

配置 pubspec.yaml 文件

# 創(chuàng)建 `assets/translations` 目錄
mkdir -p assets/translations

touch assets/translations/en.json
touch assets/translations/zh.json

en.json

{
    "hello": "Hello World",
    "title": "Flutter Demo Home Page",
    "welcome_to_flutter": "Welcome to Flutter"
}

zh.json

{
    "hello": "你好,世界",
    "title": "Flutter 演示首頁",
    "welcome_to_flutter": "歡迎來到Flutter"
}
flutter:
  assets:
    - assets/translations/

代碼示例

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hq_kocalization_stu/generated/locale_keys.g.dart';
import 'package:easy_logger/easy_logger.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  //設(shè)置日志級別
  EasyLocalization.logger.enableLevels = [
    LevelMessages.error,
    LevelMessages.warning,
  ];
  runApp(
    EasyLocalization(
      supportedLocales: const [Locale('zh'), Locale('en')],
      path: 'assets/translations',
      //是否自動(dòng)保存選擇的語言
      saveLocale: true,
      useOnlyLangCode: true,
      // 啟動(dòng)時(shí)的默認(rèn)語言
      startLocale: const Locale('zh'),
      // 回退語言
      fallbackLocale: const Locale('zh'),
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isZh = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(LocaleKeys.hello.tr()),
            Text(LocaleKeys.title.tr()),
            Text(LocaleKeys.welcome_to_flutter.tr()),
            FilledButton(
              onPressed: () {
                setState(() {
                  isZh = !isZh;
                  // 切換語言
                  context.setLocale(
                    isZh ? const Locale('zh') : const Locale('en'),
                  );
                });
              },
              child: Text(isZh ? '中文' : 'English'),
            ),
          ],
        ),
      ),
    );
  }
}

使用方式

  • 直接字符串使用tr()方法
"hello".tr()
  • 生成locale_keys.g.dart文件
flutter pub run easy_localization:generate -S ./assets/translations -f keys -o locale_keys.g.dart 
Text(
  LocaleKeys.hello.tr(),
),

參考

https://github.com/aissat/easy_localization?tab=readme-ov-file

Demo

https://github.com/HeHuiqi/hq_kocalization_stu

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容