如何在Flutter中的TextField中添加掩码?

eoxn13cs  于 2023-05-19  发布在  Flutter
关注(0)|答案(6)|浏览(122)

我试图添加一个日期掩码的textField,因为我不喜欢的日期选择器,因为出生日期,例如,它不是那么灵活。之后,从字符串转换到日期时间,我相信我可以继续该项目,提前感谢.

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

0s0u357o1#

我修改了一些东西,并设法得到预期的结果。
我创建了这个类来定义变量

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

现在没事了,谢谢

quhf5bfb

quhf5bfb2#

https://pub.dartlang.org/packages/masked_text

masked_text

一个用于屏蔽文本的软件包,所以如果你想要一个电话屏蔽,或邮政编码或任何类型的屏蔽,只要使用它:D

入门

这很简单,它是一个小部件,因为所有其他的。

new MaskedTextField
(
    maskedTextFieldController: _textCPFController,
    mask: "xx/xx/xxxx",
    maxLength: 10,
    keyboardType: TextInputType.number,
    inputDecoration: new InputDecoration(
    hintText: "Type your birthdate", labelText: "Date"),
);

'x'是你的文本将具有的正常字符。
这个示例最后重现了这样的内容:11/02/1995 .

wa7juj8i

wa7juj8i3#

我的解决方案:

class MaskTextInputFormatter extends TextInputFormatter {
  final int maskLength;
  final Map<String, List<int>> separatorBoundries;

  MaskTextInputFormatter({
    String mask = "xx.xx.xx-xxx.xx",
    List<String> separators = const [".", "-"],
  })  : this.separatorBoundries = {
          for (var v in separators)
            v: mask.split("").asMap().entries.where((entry) => entry.value == v).map((e) => e.key).toList()
        },
        this.maskLength = mask.length;

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final int newTextLength = newValue.text.length;
    final int oldTextLength = oldValue.text.length;
    // removed char
    if (newTextLength < oldTextLength) return newValue;
    // maximum amount of chars
    if (oldTextLength == maskLength) return oldValue;

    // masking
    final StringBuffer newText = StringBuffer();
    int selectionIndex = newValue.selection.end;

    // extra boundaries check
    final separatorEntry1 = separatorBoundries.entries.firstWhereOrNull((entry) => entry.value.contains(oldTextLength));
    if (separatorEntry1 != null) {
      newText.write(oldValue.text + separatorEntry1.key);
      selectionIndex++;
    } else {
      newText.write(oldValue.text);
    }
    // write the char
    newText.write(newValue.text[newValue.text.length - 1]);

    return TextEditingValue(
      text: newText.toString(),
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
e7arh2l6

e7arh2l64#

此解决方案检查日期何时超出范围(例如没有一个月像13)。效率很低,但很有效。

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class DateFormatter extends TextInputFormatter {
  final String mask = 'xx-xx-xxxx';
  final String separator = '-';

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
 if(newValue.text.length > 0) {
  if(newValue.text.length > oldValue.text.length) {
    String lastEnteredChar = newValue.text.substring(newValue.text.length-1);
    if(!_isNumeric(lastEnteredChar)) return oldValue;

    if(newValue.text.length > mask.length) return oldValue;
    if(newValue.text.length < mask.length && mask[newValue.text.length - 1] == separator) {

      String value = _validateValue(oldValue.text);
      print(value);

      return TextEditingValue(
        text: '$value$separator$lastEnteredChar',
        selection: TextSelection.collapsed(
          offset: newValue.selection.end + 1,
        ),
      );
    }

    if(newValue.text.length == mask.length) {
      return TextEditingValue(
        text: '${_validateValue(newValue.text)}',
        selection: TextSelection.collapsed(
          offset: newValue.selection.end,
        ),
      );
    }
  }
}
return newValue;
}

bool _isNumeric(String s) {
if(s == null) return false;
return double.parse(s, (e) => null) != null;
}

 String _validateValue(String s) {
String result = s;

if (s.length < 4) { // days
  int num = int.parse(s.substring(s.length-2));
  String raw = s.substring(0, s.length-2);
  if (num == 0) {
    result = raw + '01';
  } else if (num > 31) {
    result = raw + '31';
  } else {
    result = s;
  }
} else if (s.length < 7) { // month
  int num = int.parse(s.substring(s.length-2));
  String raw  = s.substring(0, s.length-2);
  if (num == 0) {
    result = raw + '01';
  } else if (num > 12) {
    result = raw + '12';
  } else {
    result = s;
  }
} else { // year
  int num = int.parse(s.substring(s.length-4));
  String raw  = s.substring(0, s.length-4);
  if (num < 1950) {
    result = raw + '1950';
  } else if (num > 2006) {
    result = raw + '2006';
  } else {
    result = s;
  }
}

print(result);
return result;
}

}
polkgigr

polkgigr5#

你可以使用flutter包mask_text_input_formatter(有超过850个赞)
使用方法:

import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';

var maskFormatter = new MaskTextInputFormatter(
  mask: '+# (###) ###-##-##', 
  filter: { "#": RegExp(r'[0-9]') },
  type: MaskAutoCompletionType.lazy
);

// In your build method
TextField(inputFormatters: [maskFormatter])
qc6wkl3g

qc6wkl3g6#

现在可以使用TextField的布尔属性“obscureText”来屏蔽输入。

相关问题