
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

class SCAccurateLengthLimitingTextInputFormatter extends TextInputFormatter {
  SCAccurateLengthLimitingTextInputFormatter(this.maxLength);

  final int maxLength;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue,
      TextEditingValue newValue,
      ) {
    final newText = newValue.text;
    final newTextCharacters = newText.characters;

    if (newTextCharacters.length > maxLength) {
      // 如果新文本超过最大长度，尝试截断
      if (oldValue.text.characters.length == maxLength) {
        return oldValue; // 已经达到最大长度，不允许再输入
      }

      // 截取前 maxLength 个字符
      final truncated = newTextCharacters.take(maxLength);
      return TextEditingValue(
        text: truncated.toString(),
        selection: TextSelection.collapsed(offset: truncated.length),
      );
    }

    return newValue;
  }
}