VS Code实现flutter多语言(官方推荐Intl)

发布于:2024-10-13 ⋅ 阅读:(48) ⋅ 点赞:(0)

1、再pubspec.yaml文件中添加:

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: any

运行 pub get packages

2、在 pubspec.yaml 文件中,启用 generate 标志

# The following section is specific to Flutter.
flutter:
  generate: true # Add this line

3、在根目录中添加一个新的 yaml 文件,命名为 l10n.yaml,添加一下内容:

arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart

4、在lib文件夹中,新建文件夹l10n, 添加app_en.arb 和 app_zh.arb模版文件(其他语言文件也是如此)。

app_en.arb文件内容:

{
    "@@locale": "en",
    "homeTitle": "Home"
    
}

app_zh.arb文件内容:

{
    "@@locale": "zh",
    "homeHitle": "首页"
 
}

5、运行项目,在dart_tool/flutter_gen/gen_l10n 中看到生成的文件。也可以运行 flutter gen-l10n 来生成本地化文件。

引入 flutter_localizations 库和 app_localizations.dart:


import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

为 MaterialApp 指定 localizationsDelegates 和 supportedLocales

return const MaterialApp(
  title: 'Flutter Demo',
  localizationsDelegates: [
    AppLocalizations.delegate, 
    GlobalMaterialLocalizations.delegate, // 为 Material 组件库提供本地化的字符串和其他值。
    GlobalWidgetsLocalizations.delegate, // 为 Cupertino 组件库提供本地化的字符串和其他值。
    GlobalCupertinoLocalizations.delegate,// 定义了默认的文本排列方向,由左到右或者由右到左。
  ],
  supportedLocales: [
    Locale('en'), // 英语
    Locale('zh'), // 中文
  ],
  home: MyHomePage(),
);

或者直接使用AppLocalizations 类,自动生成 localizationsDelegates 和 supportedLocales 列表,如下

const MaterialApp(
  title: 'Flutter Demo',
  localizationsDelegates: AppLocalizations.localizationsDelegates,
  supportedLocales: AppLocalizations.supportedLocales,
  home: MyHomePage(),
);

6、使用示例:Text(AppLocalizations.of(context)!.homeTitle)

NavigationRailDestination(
  icon: Icon(Icons.home),
  label: Text(AppLocalizations.of(context)!.homeTitle),
),