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

13 阅读1分钟

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

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

1 组字(composing)

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

2 提交

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

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,
    );
  }
}