dart - 如何在 Flutter 的 TextField 中添加 mask ?

标签 dart textfield flutter masking

我正在尝试将日期掩码添加到文本字段,因为我不喜欢日期选择器,例如,对于出生日期,它没有那么灵活。 之后,从字符串转换为日期时间,我相信我可以继续这个项目, 提前致谢。

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/

相关文章:

Dart 语言自动样式修复工具?

dart - 如何在 flutter 中降级 rxdart 插件?

flutter - _$CustomClass 显示错误 `The return type ' Type' isn't a 'CustomClass' ,由匿名闭包定义。 `

Flutter:如何使用 CustomPainter 创建生成动画

java - 如何使用 JButton 删除 textField 中某个字符的所有实例?

user-interface - Flutter中如何调用上滑面板?

android-studio - Flutter:无法编辑pubspec.yml文件,尝试编辑pubspec.yml文件时显示 “File is read-only”弹出警告

dart - 如何在 flutter 的小部件中创建内循环?

SwiftUI:类似 UITextField 的属性

solr - solr 中 text_general 和 text_en 之间的区别?