解决flutter 引入的package国际化无效的问题

解决flutter intl 引入的库内国际化失效的问题

问题发生场景

你引入了几个module,这几个module分别做了国际化,例如以下4个module ABCD,最后发现只有A的国际化效果可以使用,其他module无效:

localizationsDelegates: const [
          moduleA.S.delegate,
          moduleB.S.delegate,
          moduleC.S.delegate,
          moduleD.S.delegate,
          S.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ]

解决办法

修改引入的module的国际化相关代码:

新建my_intl.dart替换l10n.dart中的intl :

import 'package:flutter/material.dart';
import 'package:intl/src/intl_helpers.dart';
import 'package:intl/intl.dart' as RealIntl;
import '../generated/intl/messages_all.dart';
import '../generated/l10n.dart';

class Intl {
  // copied from the real intl package
  static String message(String message_str,
          {String desc: '',
          Map<String, Object> examples: const {},
          String locale,
          String name,
          List<Object> args,
          String meaning,
          bool skip}) =>
      _message(message_str, locale, name, args, meaning);

  // copied from the real intl package
  static String _message(
      String message_str, String locale, String name, List<Object> args, String meaning) {
    return myMessageLookup.lookupMessage(message_str, locale, name, args, meaning);
  }

  static MessageLookup myMessageLookup =
      UninitializedLocaleData('initializeMessages(<locale>)', null);

  static Future<S> load(Locale locale) {
    final name = locale.countryCode?.isEmpty ?? true ? locale.languageCode : locale.toString();
    final localeName = RealIntl.Intl.canonicalizedLocale(name);

    return initializeMessages(localeName).then((_) {
      final original = messageLookup;
      messageLookup = myMessageLookup;
      return initializeMessages(localeName).then((_) {
        myMessageLookup = messageLookup;
        messageLookup = original;
        RealIntl.Intl.defaultLocale = localeName;
        S.current = S();
        return S.current;
      });
    });
  }
}

将l10n.dart中的load方法指向my_intl中的load方法。

修改后的l10n.dart:

import 'package:cece_login_module/l10n/my_intl.dart';
import 'package:flutter/material.dart';

class S {
 ...
  static Future<S> load(Locale locale) => Intl.load(locale);
 ...
 

目录图:
在这里插入图片描述

相关链接github

猜你喜欢

转载自blog.csdn.net/u011272795/article/details/111176805
今日推荐