我想在输入至少 5 个字符后用破折号格式化 pin 条目。因此,每个用户输入 10 位 PIN 码时,每 5 个字符后会自动添加一个破折号。
TextField(
maxLength: 10,
keyboardType: TextInputType.text,
textCapitalization: TextCapitalization.characters,
onChanged: (text) {
pin = text;
},
textAlign: TextAlign.left,
// keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
errorText: _errorText,
icon: Icon(
Icons.dialpad,
),
labelText: '8-digit PIN',
contentPadding: EdgeInsets.symmetric(vertical: 10.0),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent, width: 2),
),
focusedErrorBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 2),
),
errorBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xFFF696969), width: 1),
),
),
),
最佳答案
您应该向 TextField
添加一个 Controller ,以便您可以控制文本字段的值。
TextField(
...
controller: _controller,
...
)
将您的 onChange
事件函数更改为如下所示:
onChanged: (String text) {
final sanitizedText = text.replaceAll('-', '');
_controller.text = _addDashes(sanitizedText);
_controller.selection = TextSelection.collapsed(offset: _controller.text.length);
},
这将获取 TextField
中的当前文本,删除破折号,并将其存储在变量中。然后,该函数使用 Controller 将 TextField
的文本替换为应用了 _addDashes
函数的已清理文本的值。此外,它会将光标移动到文本字段的末尾,因为当我们更改值时它跳到开头。
String _addDashes(String text) {
const int addDashEvery = 5;
String out = '';
for (int i = 0; i < text.length; i++) {
if (i + 1 > addDashEvery && i % addDashEvery == 0) {
out += '-';
}
out += text[i];
}
return out;
}
关于flutter - 5 个字符后自动添加破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71682157/