如何在Flutter的TextField中添加遮罩? [英] How to add a mask in a TextField in Flutter?

查看:485
本文介绍了如何在Flutter的TextField中添加遮罩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我不喜欢日期选择器,所以我试图将日期掩码添加到textField,因为例如对于出生日期,它并不那么灵活。
之后,从字符串转换为日期时间,我相信我可以继续进行该项目,
预先感谢。

I'm trying to add a date mask to a textField since I did not like the Date Picker because for date of birth, for example, it is not as nimble. After that, converting from string to datetime, I believe I can continue the project, Thanks in advance.

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; 
}


推荐答案

我修改了一些内容并进行了管理以获得预期的结果。

I modified some things and managed to get the expected result.

我创建了此类来定义变量

I created this class to define the variable

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),
); 
} 
}

最后,我在文本字段中添加了输入格式

And finally I added an inputformat to the textfield

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,
              ]
        ),

现在可以了,谢谢

这篇关于如何在Flutter的TextField中添加遮罩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆