Flutter限制输入框只能输入中文,iOS拼音打不出来?

原文地址:juejin.cn/post/758808...

知识点:输入法输入有两个阶段

1 组字(composing)

输入:bei 输入框里是拼音(未确认)

2 提交

选择「北」 中文字符真正上屏

js 复制代码
class UniversityNameInputFormatter extends TextInputFormatter {
  UniversityNameInputFormatter({this.maxLength = 40});

  final int maxLength;

  static final RegExp _disallowed =
      RegExp(r'[^a-zA-Z0-9\u4E00-\u9FFF-\s]');
  static final RegExp _multiHyphen = RegExp(r'-{2,}');
  static final RegExp _leadingHyphen = RegExp(r'^-+');
  static final RegExp _trailingHyphen = RegExp(r'-+$');

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    // iOS 中文拼音组字阶段
    if (!newValue.composing.isCollapsed) {
      return newValue;
    }

    var text = newValue.text;
    if (text.isEmpty) return newValue;

    text = text.replaceAll(_disallowed, '');
    text = text.replaceAll(_multiHyphen, '-');
    text = text.replaceAll(_leadingHyphen, '');
    text = text.replaceAll(_trailingHyphen, '');

    if (text.length > maxLength) {
      text = text.substring(0, maxLength);
    }

    if (text == newValue.text) return newValue;

    int clamp(int o) => o.clamp(0, text.length);

    return TextEditingValue(
      text: text,
      selection: TextSelection(
        baseOffset: clamp(newValue.selection.baseOffset),
        extentOffset: clamp(newValue.selection.extentOffset),
      ),
      composing: TextRange.empty,
    );
  }
}
相关推荐
Flutter OH12 小时前
Flutter OH平台 DFX 问题定位导航
flutter
恋猫de小郭14 小时前
AI 时代,也许你的 Flutter 需要一套 Dartastic OpenTelemetry 监控
android·前端·flutter
等....15 小时前
Flutter创建
flutter
Privasa-隐私实验室15 小时前
跨端技术选型|Flutter搭建隐私加密App,安卓与iOS双端差异适配实战
android·笔记·安全·flutter·ios·隐私安全·aes-256
Flutter OH1 天前
Flutter OH 外接纹理问题定位指南
flutter
未来猫咪花1 天前
Everything is ViewModel:让状态管理回到对象世界
android·flutter·ios
Flutter OH1 天前
Flutter OH 日志抓取与过滤指南
flutter
Flutter OH1 天前
Flutter OH 内存与 GPU 问题定位指南
flutter
Flutter OH1 天前
Flutter OH 多设备适配问题定位指南
flutter
律宏阔1 天前
Flutter Hooks 与 flutter_map_animations 冲突:第二次地图动画报错的解决方案
flutter