使用flutter pub包 easy_localization

1.用終端在桌面創(chuàng)建flutter項目 use_easy_localization 并導入pub包

flutter create use_easy_localization

flutter pub add easy_localization 

2.新建resources/langs文件夾,加入語言配置json文件,配置中英文兩種語言。

en.json

{
    "title": "HelloWorld",
    "content": {
        "message": "HelloWorld,HelloWorld,HelloWorld"
    }
}

en-US.json

{
    "title": "HelloWorld",
    "content": {
        "message": "HelloWorld,HelloWorld,HelloWorld"
    }
}

zh.json

{
    "title": "世界",
    "content": {
        "message": "世界,世界,世界"
    }
}

zh-CH.json

{
    "title": "世界",
    "content": {
        "message": "世界,世界,世界"
    }
}

3.在 pubspec.yal 配置資源路徑

flutter:
  assets:
    - resources/langs/
    

4.在 ios/Runner/Info.plist 添加key

  <key>CFBundleLocalizations</key>
    <array>
        <string>en</string>
        <string>zh</string>
    </array> 

5.添加 EasyLocalization 組件

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();

  runApp(
    EasyLocalization(
      child: const MyApp(),
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('zh', 'CH'),
      ],
      path: 'resources/langs',
      assetLoader: const CodegenLoader(),
    ),
  );
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      title: '多語言',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: '多語言'),
    );
  }
}

6.切換語言

/// 切換語言
  void _changeLocale() async {
    if (context.locale.toString() == 'zh_CH') {
      await context.setLocale(context.supportedLocales[0]);
    } else {
      await context.setLocale(context.supportedLocales[1]);
    }
  }

7.完整代碼

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

import 'generated/codegen_loader.g.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();

  runApp(
    EasyLocalization(
      child: const MyApp(),
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('zh', 'CH'),
      ],
      path: 'resources/langs',
      assetLoader: const CodegenLoader(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      title: '多語言',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: '多語言'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  /// 切換語言
  void _changeLocale() async {
    if (context.locale.toString() == 'zh_CH') {
      await context.setLocale(context.supportedLocales[0]);
    } else {
      await context.setLocale(context.supportedLocales[1]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(LocaleKeys.title).tr(),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              LocaleKeys.content.tr(gender: "message"),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _changeLocale,
        tooltip: '切換語言',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Github代碼

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容