Flutter ios 国际化(复制粘贴 中英文切换等问题)

前提

在做flutter ios 国际化的时候遇到长按文本框崩溃的问题,然后google到一堆写法是重写cupertinoLocalization的奇怪做法,然后还千篇一律都是这么改的,其实不用那么麻烦,一个代码就可以解决的问题

Flutter 中文网的例子

因为FLutter默认值支持美国英语的本地化,所以需要用到flutter_localizations的库,目前,软件包支持15中语言。

引入:flutter_localizations

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

使用:

import 'package:flutter_localizations/flutter_localizations.dart';

new MaterialApp(
 localizationsDelegates: [
   // ... app-specific localization delegate[s] here
   GlobalMaterialLocalizations.delegate,
   GlobalWidgetsLocalizations.delegate,
 ],
 supportedLocales: [
    const Locale('en', 'US'), // English
    const Locale('he', 'IL'), // Hebrew
    // ... other locales the app supports
  ],
  // ...
)

问题1:

按照Flutter中文网提供的这个例子来使用,在android中已经可以进行语言切换,实现对应的中英文切换了,但是在iphone中通过长按输入框,就会出错(get方法为空),提示为:

The getter 'pasteButtonLabel' was called on null.
Receiver: null
Tried calling: pasteButtonLabel

方案1:

这个错误,在天星银行里面也有,修复之后不会出现中文文案的提示。具体的修复代码如下:

class CupertinoLocalizationsDelegate extends LocalizationsDelegate<CupertinoLocalizations> {
  const CupertinoLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => true;

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

  @override
  bool shouldReload(CupertinoLocalizationsDelegate old) => false;

  @override
  String toString() => 'DefaultCupertinoLocalizations.delegate(zh_CH)';
}

--------------------------------------

localizationsDelegates: [
   // ... app-specific localization delegate[s] here
   GlobalMaterialLocalizations.delegate,
   GlobalWidgetsLocalizations.delegate,
   CupertinoLocalizationsDelegate(),
 ],


添加如上代码之后,长按ios 会出现英文的cut、paste等文案,但是不会随着语言的切换本地化语言

原因是重写了LocalizationsDelegate,在isSupported返回true,不管当前是什么语言,我统统给你返回英文的默认文案(DefaultCupertinoLocalizations),改法显然是错误的。

方案2:

 @override
  Future<CupertinoLocalizations> load(Locale locale) {
    if (locale.languageCode == 'zh') {
      print('locale.languageCode');
      return ChineseCupertinoLocalizations.load(locale);
    }
    return DefaultCupertinoLocalizations.load(locale);
  }

ChineseCupertinoLocalizations是 新写的类 继承 CupertinoLocalizations 实现所有的method

class ChineseCupertinoLocalizations implements CupertinoLocalizations {
    
    .....
    
  @override
  String get cutButtonLabel => '剪切';

  @override
  String get copyButtonLabel => '复制';

  @override
  String get pasteButtonLabel => '粘贴';

  @override
  String get selectAllButtonLabel => '全选';
  
  .....
}

经过上述操作,问题是解决了,但是感觉不太对:

1、flutter_localizations 本身支持十几种语言,android 切换没有问题,ios 却有问题。

2、如果国际化更多的语言,难道要每个语言实现一遍CupertinoLocalizations,思路明显有问题。

分析

MaterialApp 提供的参数localizationsDelegates列表中的元素是生本地集合的工厂,其中GlobalMaterialLocalizations.delegate为Material Components库提供了本地化的字符串和其他值。GlobalWidgetsLocalizations.delegate定义widget默认的文本方向,从左到右或从右到左(如沙特语言)。

LocalizationsDelegate是何物?我们看一下源码

abstract class LocalizationsDelegate<T> {

  bool isSupported(Locale locale);
  
  Future<T> load(Locale locale);
  
  bool shouldReload(covariant LocalizationsDelegate<T> old);
  Type get type => T;

  @override
  String toString() => '${objectRuntimeType(this, 'LocalizationsDelegate')}[$type]';
}

LocalizationsDelegate 提供了 三个关键函数:分别是isSupportedloadshouldReload

flutter为了减小包的大小,仅仅提供了英文的MaterialLocalizationsCupertinoLocalizations的实现,分别是DefaultMaterialLocalizationsDefaultCupertinoLocalizations所以在语言是英文的情况下,即使不引入flutter_localizations库 一些系统的文本是没有问题的,但是本地语言是英文之外的语言,就需要这个库了。

按照官方的写法引入:

localizationsDelegates: [
        // 本地化代理
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],

Material Components库是支持iOS、android、web 三段通用的风格,所以正常提供GlobalMaterialLocalizations.delegate提供的本地化字符串和其他值,应该是三段通用的。但是从现象上看是有问题的(下面解释),查看GlobalMaterialLocalizations.delegate的实现中有一个函数:

 static const List<LocalizationsDelegate<dynamic>> delegates = <LocalizationsDelegate<dynamic>>[
    GlobalCupertinoLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
  ];

delegates直接提供了GlobalCupertinoLocalizationsGlobalMaterialLocalizations ,说明flutter_localizations也是支持iOS的国际化设置的。

修改MaterialApp中的参数设置:

      localizationsDelegates: [
        // 本地化代理
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''), // 美国英语
        const Locale('zh', 'HK'), // 中文
        const Locale('ja', ''), // 日语
      ],
       locale: const Locale('en', ''),

在加入GlobalCupertinoLocalizations之后就可以的支持iOS的国际化操作了。

继续查看GlobalMaterialLocalizations中,查看继承自LocalizationsDelegate_MaterialLocalizationsDelegate

isSupported中看到支持的语言:

final Set<String> kMaterialSupportedLanguages = HashSet<String>.from(const <String>[
  'af', // Afrikaans
  'am', // Amharic
  'ar', // Arabic
  'as', // Assamese
  'az', // Azerbaijani
  'be', // Belarusian
  'bg', // Bulgarian
  'bn', // Bengali Bangla
  'bs', // Bosnian
  ......//后面还有好多
]);

load的的返回中:

return SynchronousFuture<MaterialLocalizations>(getMaterialTranslation(
        locale,
        fullYearFormat,
        compactDateFormat,
        shortDateFormat,
        mediumDateFormat,
        longDateFormat,
        yearMonthFormat,
        shortMonthDayFormat,
        decimalFormat,
        twoDigitZeroPaddedFormat,
      ));

根据getMaterialTranslation 返回对应语言场景下的继承自GlobalMaterialLocalizations的具体实例。

GlobalMaterialLocalizations getMaterialTranslation(
  Locale locale,
  intl.DateFormat fullYearFormat,
  intl.DateFormat compactDateFormat,
  intl.DateFormat shortDateFormat,
  intl.DateFormat mediumDateFormat,
  intl.DateFormat longDateFormat,
  intl.DateFormat yearMonthFormat,
  intl.DateFormat shortMonthDayFormat,
  intl.NumberFormat decimalFormat,
  intl.NumberFormat twoDigitZeroPaddedFormat,
) {
  switch (locale.languageCode) {
    case 'af':
      return MaterialLocalizationAf(fullYearFormat: fullYearFormat, compactDateFormat: compactDateFormat, shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, yearMonthFormat: yearMonthFormat, shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat);
    case 'am':
      return MaterialLocalizationAm(fullYearFormat: fullYearFormat, compactDateFormat: compactDateFormat, shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, yearMonthFormat: yearMonthFormat, shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat);
    case 'ar':
      return MaterialLocalizationAr(fullYearFormat: fullYearFormat, compactDateFormat: compactDateFormat, shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, yearMonthFormat: yearMonthFormat, shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat);
      ......//很多语言
    

App通过启动,或者切换语言的时候,替换MaterialApp中的'locale'对象来切换语言,同时,切换的语言对象要在supportedLocales中,否则默认返回supportedLocales中的第一个语言,如果一个都没有,默认返回英文

supportedLocales: [
        const Locale('ja', ''), // 日语
        const Locale('en', ''), // 美国英语
        const Locale('zh', 'HK'), // 中文

        //其它Locales
      ],
 locale: const Locale('zh', ''),

问题:

既然GlobalMaterialLocalizations是iOS和android 通用的风格,在Flutter中文网 介绍的接入国际化的时候也只提到了GlobalMaterialLocalizations感觉这明显是有问题的。

DefalutCupertinoLocalization中我们检索cutButtonLabel属性,我们看一下那些地方在使用:

内容:

  @override
  String get cutButtonLabel => 'Cut';

  @override
  String get copyButtonLabel => 'Copy';

  @override
  String get pasteButtonLabel => 'Paste';

结果发现有两处地方在使用:

flutter > lib > src > material > text_selection.dart
flutter > lib > scr > cupertino > text_selection.dart

在这两个textSelection的build函数中,获取的Localizations分别是materialcupertino的:

@override
  Widget build(BuildContext context) {
    // Don't render the menu until the state of the clipboard is known.
    if (widget.handlePaste != null
        && _clipboardStatus.value == ClipboardStatus.unknown) {
      return const SizedBox(width: 0.0, height: 0.0);
    }
    print('text_selected---------------------------CupertinoLocalizations');
    final List<Widget> items = <Widget>[];
    final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
    final EdgeInsets arrowPadding = widget.isArrowPointingDown
      ? EdgeInsets.only(bottom: _kToolbarArrowSize.height)
      : EdgeInsets.only(top: _kToolbarArrowSize.height);
    final Widget onePhysicalPixelVerticalDivider =
        SizedBox(width: 1.0 / MediaQuery.of(context).devicePixelRatio);

@override
  Widget build(BuildContext context) {
    // Don't render the menu until the state of the clipboard is known.
    if (widget.handlePaste != null
        && _clipboardStatus.value == ClipboardStatus.unknown) {
      return const SizedBox(width: 0.0, height: 0.0);
    }
    print('text_selected---------------------------MaterialLocalizations');
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
    final List<_ItemData> itemDatas = <_ItemData>[
      if (widget.handleCut != null)
        _ItemData(widget.handleCut, localizations.cutButtonLabel),
      if (widget.handleCopy != null)
        _ItemData(widget.handleCopy, localizations.copyButtonLabel),
      if (widget.handlePaste != null
          && _clipboardStatus.value == ClipboardStatus.pasteable)
        _ItemData(widget.handlePaste, localizations.pasteButtonLabel),
      if (widget.handleSelectAll != null)
        _ItemData(widget.handleSelectAll, localizations.selectAllButtonLabel),
    ];

加上print之后发现,在iOS设备上加载的cupertinotext_selected,android上是materialtext_selected ,

由此真相大白。

正常实现系统文本的国际化只需要在MaterialApp的初始化中加入:

  localizationsDelegates: [
        // 本地化代理
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容

  • 概述 国际化的认识 国际化的适配 国际化的工具 一、国际化的认识 开发一个App,如果我们的App需要面向不同的语...
    IIronMan阅读 713评论 0 2
  • 前言 如果APP有需要支持多种语言,就需要支持国际化,无论是android和ios,现在针对flutter的国际化...
    lebonbill阅读 10,691评论 4 6
  • 国际化:支持多种语言。为应用程序支持的每种语言设置本地化值,如文本(语言差异)、布局(阅读方向差异)、图片(国旗)...
    平安喜乐698阅读 3,403评论 0 3
  • 一、前言 从 2015 年接触 Flutter 到现在也有两年多时间,在这期间我并没有正真地去了解这个神奇的框架,...
    _番茄沙司阅读 35,208评论 21 48
  • 今天项目中添加了一个需求,App设置中有个语言切换,需要实现的效果是中英繁切换,针对APP国际化进行操作,使APP...
    本客阅读 1,668评论 0 4