美文网首页flutterdart
Flutter ios 国际化(复制粘贴 中英文切换等问题)

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

作者: 陈贤森 | 来源:发表于2020-12-24 15:33 被阅读0次

    前提

    在做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,
          ],
    

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/kzumnktx.html