Flutter支持多语言

通过VSCode插件来配置Flutter的多语言支持。

Flutter Intl

  • 安装VS Code插件 Flutter Intl
  • VS Code中执行命令Flutter Intl: Initialize
  • 设置多语言依赖
    1
    2
    3
    4
    dependencies:
    // Other dependencies...
    flutter_localizations:
    sdk: flutter
  • 在项目入口加入localizationsDelegatessupportedLocales
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import 'package:flutter_localizations/flutter_localizations.dart';
    import 'generated/l10n.dart';

    class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    return new MaterialApp(
    localizationsDelegates: [
    S.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
    ],
    supportedLocales: S.delegate.supportedLocales,
    title: 'Flutter Demo',
    home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
    }
    }
  • 添加其他语言, 执行命令Flutter Intl: Add locale
  • 修改lib/l10n目录下对应的键值
    1
    2
    3
    {
    "Welcome":"欢迎"
    }
  • 通过S.of(context).Welcome来引用
  • 通过S.load(Locale('cn')) 来修改当前语言环境

通过ICU消息格式实现条件翻译

例如实现根据当前语言环境返回特定的翻译语言

  • intl_en.arb 内容
    1
    2
    3
    {
    "local":"{local, select, en {English} cn {Chinese} other {Chinese}}"
    }
  • intl_cn.arb 内容
    1
    2
    3
    {
    "local":"{local, select, en {英文} cn {简体中文} other {简体中文}}"
    }
  • 使用
    1
    S.of(context).local(locale.languageCode)

引用

发布