支持 Flutter 常量字符串的多种语言

Supporting multiple languages for constant strings in Flutter

我想开始将我所有的常量字符串(如标签等)放到一个可以在稍后阶段翻译的地方。

Flutter 是如何处理的?

我在 gitter 上询问,得到以下信息:

Translation/Internationalization isn't a feature we consider "done" yet. https://pub.dartlang.org/packages/intl works in Flutter. We have a bug tracking this more generally: flutter/flutter#393

More complete internationalization (i18n) and accessibility support are two of the big arcs of work ahead of Flutter in the coming months. Another example of i18n work we have planned, is completing Right-to-left (RTL) layouts for our provided Widgets (e.g. teaching the Material library's Scaffold to place the Drawer on the left when the locale is an RTL language). RTL Text support works today, but there are no widgets which are out-of-the-box RTL-layout aware at this moment.

  1. 创建 Localizations.dart 文件

  2. 将以下代码添加到该文件:


import 'dart:async';
import 'package:flutter/material.dart';

import 'package:flutter/foundation.dart' show SynchronousFuture;
class DemoLocalizations {
  DemoLocalizations(this.locale);
  final Locale locale;
  static DemoLocalizations of(BuildContext context) {
    return Localizations.of<DemoLocalizations>(context, DemoLocalizations);
  }
  static Map<String, Map<String, String>> _localizedValues = {
    'en': {
      'title': 'App title',
      'googleLogin': 'Login with Google'
    },
    'es': {
      'title': 'Título de App',
      'googleLogin': 'Conectar con Google'
    },
  };
  String get title {
    return _localizedValues[locale.languageCode]['title'];
  }
  String get googleLogin {
    return _localizedValues[locale.languageCode]['googleLogin'];
  }
}
class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations> {
  const DemoLocalizationsDelegate();
  @override
  bool isSupported(Locale locale) => ['en', 'es'].contains(locale.languageCode);

  @override
  Future<DemoLocalizations> load(Locale locale) {
    // Returning a SynchronousFuture here because an async "load" operation
    // isn't needed to produce an instance of DemoLocalizations.
    return new SynchronousFuture<DemoLocalizations>(new DemoLocalizations(locale));
  }
  @override
  bool shouldReload(DemoLocalizationsDelegate old) => false;
}

  1. Localizations.dart 导入到您使用字符串的文件中。

  2. MaterialApp

    中添加代表DemoLocalizationsDelegate
MaterialApp(
  localizationsDelegates: [
   MyLocalizationsDelegate(),
  ],
...
)
  1. new Text(DemoLocalizations.of(context).title),
  2. 代替new Text("App Title"),

对于每个要本地化的新字符串,您需要将翻译后的文本添加到每种语言的映射中,然后添加 String get... 行。 它有点麻烦,但它可以满足您的需要。

这是对一种方法的快速概述。 您可以在 Flutter 文档中阅读更多相关信息:https://flutter.io/tutorials/internationalization/