ellipsize method

String ellipsize(
  1. int length,
  2. String endChars,
  3. bool isAccurate
)

截断字符 text处理文体 length最大长度(以字符计) endChars末尾显示字符 isAccurate是否精确统计

Implementation

String ellipsize(int length, String endChars, bool isAccurate) {
  String text = this?.trim() ?? "";
  int len = text.length;
  int count = 0;
  StringBuffer builder = new StringBuffer();
  for (int i = 0; i < len; i++) {
    var c = text.substring(i, i + 1);
    if (isAccurate && RegExp("[\u4e00-\u9fa5]").hasMatch(c)) {
      count += 2;
    } else {
      count++;
    }
    if (count <= length) {
      builder.write(c);
    } else {
      break;
    }
  }
  if (len >= length) {
    builder.write(endChars);
  }
  return builder.toString().trim();
}