Flutter之國際化多語言

1.用多個文件來配各個國家的語言:

在lib 文件夾中創建新文件夾名爲locale,目前文件配置支持中文和美文:

lib/locale/i18n_zh.json
lib/locale/i18n_en.json
json格式:
{
  "hello" : "Hello~",
  "hello2" : "Hello~",
  "home": "home",
  "classify": "classify",
  "shopping_cart": "Shopping Cart",
  "member_center": "Member Center",
  "peoples_life": "People's life+"
}

2.在pubspec.yaml中配置第三方插件:

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations: #多語言
    sdk: flutter

3..在pubspec.yaml中配置assets的信息:

 assets:
     - lib/locale/i18n_en.json
     - lib/locale/i18n_zh.json

4.語言工具類lib/utils/translation.dart:


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

class Translations {
  Translations(Locale locale) {
    this.locale = locale;
    _localizedValues = null;
  }

  Locale locale;
  static Map<dynamic, dynamic> _localizedValues;

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

  String text(String key) {
    try {
      String value = _localizedValues[key];
      if(value == null || value.isEmpty) {
        return englishText(key);
      } else {
        return value;
      }
    } catch (e) {
      return englishText(key);
    }
  }

  String englishText(String key) {
    if( _localizedValues=null){
      return'** $key not fodun';
    }
    return _localizedValues[key] ?? '** $key not fodun';
  }

  static Future<Translations> load(Locale locale) async {
    Translations translations = new Translations(locale);
    String jsonContent = await rootBundle.loadString("lib/locale/i18n_${locale.languageCode}.json");
    _localizedValues = json.decode(jsonContent);
    return translations;
  }

  get currentLanguage => locale.languageCode;
}

class TranslationsDelegate extends LocalizationsDelegate<Translations> {
  const TranslationsDelegate();

  @override
  bool isSupported(Locale locale) => applic.supportedLanguages.contains(locale.languageCode);

  @override
  Future<Translations> load(Locale locale) => Translations.load(locale);

  @override
  bool shouldReload(TranslationsDelegate old) => false;
}

class SpecificLocalizationDelegate extends LocalizationsDelegate<Translations> {
  final Locale overriddenLocale;

  const SpecificLocalizationDelegate(this.overriddenLocale);

  @override
  bool isSupported(Locale locale) => overriddenLocale != null;

  @override
  Future<Translations> load(Locale locale) => Translations.load(overriddenLocale);

  @override
  bool shouldReload(LocalizationsDelegate<Translations> old) => true;
}

typedef void LocaleChangeCallback(Locale locale);
class APPLIC {
  // List of supported languages
  final List<String> supportedLanguages = ['en','zh'];
  // Returns the list of supported Locales
  Iterable<Locale> supportedLocales() => supportedLanguages.map<Locale>((lang) => new Locale(lang, ''));
  // Function to be invoked when changing the working language
  LocaleChangeCallback onLocaleChanged;
  ///
  /// Internals
  ///
  static final APPLIC _applic = new APPLIC._internal();
  factory APPLIC(){
    return _applic;
  }
  APPLIC._internal();
}
APPLIC applic = new APPLIC();

4.在main.dart類中配置:

class MyApp  extends StatefulWidget {
    @override
  _MyAppState createState() => new _MyAppState();
  }

class _MyAppState extends State<MyApp> {

  SpecificLocalizationDelegate _localeOverrideDelegate;
  @override
  void initState(){
    super.initState();
 
    _localeOverrideDelegate = new SpecificLocalizationDelegate(null);
    applic.onLocaleChanged = onLocaleChange;
  }

  // 改變語言時的應用刷新核心方法:
  onLocaleChange(Locale locale){
    setState((){
      _localeOverrideDelegate = new SpecificLocalizationDelegate(locale);
    });
  }


  @override
  Widget build(BuildContext context) {

    final router = Router();
    Routes.configureRoutes(router);
    Application.router=router;
    

    return Container(
      
      child: MaterialApp(
        localizationsDelegates: [
          // 註冊一個新的delegate
            _localeOverrideDelegate, 

         // 指向默認的處理翻譯邏輯的庫 
            const TranslationsDelegate(), 

            // 本地化的代理類
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
        ],
        supportedLocales: applic.supportedLocales(),
        debugShowCheckedModeBanner: false,
        onGenerateRoute: Application.router.generator,
        theme: ThemeData(
          primaryColor:Colors.pink,
        ),
        home:IndexPage()
      ),
    );
  }
}

5.運用方法:

 BottomNavigationBarItem(
                    icon:Icon(CupertinoIcons.home),
                    title:Text(Translations.of(context).text("home"))
                ),

6.切換語言的方法:

調用applic.onLocaleChanged(new Locale('en',''));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章