Flutter 实现卡号格式的显示和输入

卡号后自动使用空格或自定义分隔,如:1234 5678 9012 3456 789

 

扩展String类,增加分隔方法

extension StringSeprate on String {
  String stringSeprate({int count = 4, String separator = ','}) {
    if (this.isEmpty) {
      return '';
    }
    if (count < 1) {
      return this;
    }
    if (count >= this.length) {
      return this;
    }
    var str = this.replaceAll(separator, "");
    var chars = str.runes.toList();
    var namOfSeparation =
        (chars.length.toDouble() / count.toDouble()).ceil() - 1;

    int len = chars.length + namOfSeparation.round();
    var separatedChars = List.filled(len, "");
    var j = 0;
    for (var i = 0; i < chars.length; i++) {
      separatedChars[j] = String.fromCharCode(chars[i]);
      if (i > 0 && (i + 1) < chars.length && (i + 1) % count == 0) {
        j += 1;
        separatedChars[j] = separator;
      }

      j += 1;
    }

    return separatedChars.join();
  }
}

 文本显示

 Text('1212121212121212'.stringSeprate(count: 4)),

输入卡号时,显示分割,在TextField新增inputFormatters

/// TextField 中增加inputFormatters

 inputFormatters: [
                //每个字符使用空格分隔一次
                TextInputFormatter.withFunction((oldValue, newValue) =>
                    TextEditingValue(
                        text: newValue.text.stringSeparate(
                            separator: ' ',count:4)))
              ],

你可能感兴趣的:(flutter,源码类,flutter)