flutter如何实现卡号格式的输入(自动带空格分割)?

码云
2020-11-09 10:31

flutter如何实现卡号格式的输入,输入卡号后自动使用空格分隔,如:1234 5678 9012 3456 789。

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

class TestWidget extends StatelessWidget {
  TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _textEditingController,
              //重点:指定InputFormatter格式化输入
              inputFormatters: [
                //每4个字符使用空格分隔一次
                TextInputFormatter.withFunction((oldValue, newValue) =>
                    TextEditingValue(
                        text: newValue.text.stringSeparate(
                            separator: ' ',count:4, fromRightToLeft: false)))
              ],
              onChanged: (String value) {
                if (value == null) return;
                _textEditingController.selection = TextSelection.fromPosition(
                    TextPosition(
                        offset: value.length, affinity: TextAffinity.upstream));
              },
            ),
          ],
        ),
      ),
    );
  }
}

//扩展String,增加字符串分隔方法
extension StringSeprate on String {
  String stringSeparate({int count = 3, String separator = ",", bool fromRightToLeft = true}) {
    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;
    var separatedChars = List(chars.length + namOfSeparation.round());
    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 fromRightToLeft
        ? String.fromCharCodes(separatedChars.join().runes.toList().reversed)
        : separatedChars.join();
  }
}

 

看着代码一大堆,其实不用这么麻烦,主要是两点:

1)写一个方法自动分隔字符串(这里扩展了String,其实可以自己写个util完成相同的效果)

2)将这个分隔方法包装成InputFormatter并应用到TextField控件即可。

全部评论

相关文章