如上图,此类需求,身份证号码输入需要格式处理
import 'package:flutter/material.dart';
class CardIdItem extends StatefulWidget {
const CardIdItem({Key? key}) : super(key: key);
@override
State<CardIdItem> createState() => _CardIdItemState();
}
class _CardIdItemState extends State<CardIdItem> {
final TextEditingController codeEdit = TextEditingController();
String _oldInputCodeText = "";
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all( 20),
height: 56,
// color: Colors.blueAccent,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: 70,
height: 30,
alignment: Alignment.centerLeft,
child: const Text(
"身份证",
style: TextStyle(
fontSize: 16),
),
),
Flexible(
child: TextField(
controller: codeEdit,
keyboardType: const TextInputType.numberWithOptions(signed: true),
maxLength: 21,
obscureText: false,
onChanged: (value) {
_splitPhoneNumber(value);
},
style: const TextStyle(fontSize: 16),
decoration: const InputDecoration(
// contentPadding: EdgeInsets.only(top: 4.px),
counterText: "", //此处控制最大字符是否显示
hintText: "请输入身份证",
hintStyle: TextStyle(color: Colors.grey),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.grey)),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.grey)),
),
),
),
],
),
);
}
void _splitPhoneNumber(String text) {
//输入身份证号格式
String codeText = getIdCode(text); //去除空格
//记录此时光标位置
int currentSelection = codeEdit.selection.base.offset;
//删除空格,相当于删除空格前一位
if (_oldInputCodeText.length > text.length &&
codeText.isNotEmpty &&
_oldInputCodeText.substring(currentSelection, currentSelection + 1) ==
" ") {
String oldStartString =
_oldInputCodeText.substring(0, currentSelection + 1);
//定位删除空格位置
oldStartString = getIdCode(oldStartString);
codeText = codeText.replaceRange(
oldStartString.length - 1, oldStartString.length, "");
}
String newCodeText = "";
for (int index = 0; index < codeText.length; index++) {
if (index == 5 || index == 9 || index == 13) {
newCodeText = "$newCodeText${codeText[index]} ";
} else {
newCodeText = newCodeText + codeText[index];
}
}
_oldInputCodeText = newCodeText;
codeEdit.text = newCodeText;
if (newCodeText.length > text.length) {
currentSelection = currentSelection + 1;
} else if (newCodeText.length < text.length) {
currentSelection = currentSelection - 1;
}
//设置光标位置
codeEdit.selection = TextSelection.fromPosition(TextPosition(
affinity: TextAffinity.downstream, offset: currentSelection));
}
String getIdCode(String text) {
return text.replaceAll(RegExp(r"\s+\b|\b\s"), "");
}
}