我正在尝试将日期掩码添加到文本字段,因为我不喜欢日期选择器,例如,对于出生日期,它没有那么灵活。 之后,从字符串转换为日期时间,我相信我可以继续这个项目, 提前致谢。
static final TextEditingController _birthDate = new TextEditingController();
new TextFormField(
controller: _birthDate,
maxLength: 10,
keyboardType: TextInputType.datetime,
validator: _validateDate
), String _validateDate(String value) {
if(value.isEmpty)
return null;
if(value.length != 10)
return 'Enter date in DD / MM / YYYY format';
return null;
}
最佳答案
我修改了一些东西,并设法得到了预期的结果。
我创建了这个类来定义变量
static final _UsNumberTextInputFormatter _birthDate = new _UsNumberTextInputFormatter();
class _UsNumberTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue ) {
final int newTextLength = newValue.text.length;
int selectionIndex = newValue.selection.end;
int usedSubstringIndex = 0;
final StringBuffer newText = new StringBuffer();
if (newTextLength >= 3) {
newText.write(newValue.text.substring(0, usedSubstringIndex = 2) + '/');
if (newValue.selection.end >= 2)
selectionIndex ++;
}
if (newTextLength >= 5) {
newText.write(newValue.text.substring(2, usedSubstringIndex = 4) + '/');
if (newValue.selection.end >= 4)
selectionIndex++;
}
if (newTextLength >= 9) {
newText.write(newValue.text.substring(4, usedSubstringIndex = 8));
if (newValue.selection.end >= 8)
selectionIndex++;
}
// Dump the rest.
if (newTextLength >= usedSubstringIndex)
newText.write(newValue.text.substring(usedSubstringIndex));
return new TextEditingValue(
text: newText.toString(),
selection: new TextSelection.collapsed(offset: selectionIndex),
);
}
}
最后我在文本字段中添加了一个输入格式
new TextFormField(
maxLength: 10,
keyboardType: TextInputType.datetime,
validator: _validateDate,
decoration: const InputDecoration(
hintText: 'Digite sua data de nascimento',
labelText: 'Data de Nascimento',
),
inputFormatters: <TextInputFormatter> [
WhitelistingTextInputFormatter.digitsOnly,
// Fit the validating format.
_birthDate,
]
),
现在没事了,谢谢
关于dart - 如何在 Flutter 的 TextField 中添加 mask ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008786/