Flutter 中 国际化

245 阅读2分钟

Flutter中的国际化是指将应用程序的文本和其他本地化内容适配到不同的语言和地区,以便应用程序可以在全球范围内为不同的用户提供本地化的体验。Flutter提供了一种简单而强大的方式来实现国际化,通过Intl包和flutter_localizations库,您可以轻松地将应用程序本地化为多种语言。

以下是一个简单的国际化示例代码,演示了如何在Flutter应用程序中实现国际化:

首先,需要在pubspec.yaml文件中添加intlflutter_localizations的依赖:

dependencies:
  flutter:
    sdk: flutter
  intl: ^0.17.0
  flutter_localizations:
    sdk: flutter

然后,创建一个包含本地化文本的资源文件。在lib目录下创建一个名为l10n的文件夹,然后在该文件夹中创建两个文件:app_localizations.dartapp_localizations_<language_code>.dart,例如app_localizations_en.dartapp_localizations_fr.dart。这些文件将包含应用程序的本地化文本。

app_localizations.dart

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

class AppLocalizations {
  final Locale locale;

  AppLocalizations(this.locale);

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

  static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();

  Map<String, String> _localizedStrings;

  Future<bool> load() async {
    String jsonString = await rootBundle.loadString('assets/i18n/${locale.languageCode}.json');
    Map<String, dynamic> jsonMap = json.decode(jsonString);
    _localizedStrings = jsonMap.map((key, value) => MapEntry(key, value.toString()));
    return true;
  }

  String translate(String key) {
    return _localizedStrings[key];
  }
}

class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  const _AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['en', 'fr'].contains(locale.languageCode);
  }

  @override
  Future<AppLocalizations> load(Locale locale) async {
    AppLocalizations localizations = AppLocalizations(locale);
    await localizations.load();
    return localizations;
  }

  @override
  bool shouldReload(LocalizationsDelegate<AppLocalizations> old) {
    return false;
  }
}

app_localizations_en.dart

{
  "title": "Hello World!",
  "greet": "Hello, {name}!",
  "button_text": "Press Me"
}

app_localizations_fr.dart

{
  "title": "Bonjour le monde!",
  "greet": "Bonjour, {name}!",
  "button_text": "Appuie sur moi"
}

接下来,在应用程序的入口处,通过MaterialApplocalizationsDelegatessupportedLocales属性配置本地化支持:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:my_app/l10n/app_localizations.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('en', 'US'),
        Locale('fr', 'FR'),
      ],
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var appLocalization = AppLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(appLocalization.translate('title')),
      ),
      body: Center(
        child: Text(
          appLocalization.translate('greet', {'name': 'John'}),
        ),
      ),
    );
  }
}

HomePage中,我们使用了AppLocalizations来获取本地化的文本,并使用translate方法来翻译文本。注意,我们可以传递参数给翻译的文本,以实现更灵活的本地化。

通过以上步骤,您就可以实现Flutter应用程序的国际化了。根据需要,您可以添加更多语言的本地化文本,并在应用程序中支持这些语言。