Flutter–如何解决删除问题TextInputFormatter



我的输入工作正常,但无法删除符号。如何做到这一点?

我只想将信用卡中的日期格式化(如下图所示:01/25(,如果1个符号>1我写0+符号,否则我只写符号

这里的代码

class DateFormat extends TextInputFormatter {
//Formatting to *#/## (if (*>1) *=0)
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final newTextLength = newValue.text.length;
int selectionIndex = newValue.selection.end;
int usedSubstringIndex = 1;
final newTextBuffer = StringBuffer();
if (newTextLength >= 1) {
if (newValue.text.startsWith(RegExp(r'[2-9]'))) {
newTextBuffer.write('0${newValue.text.substring(0, 1)}');
if (newValue.selection.end >= 1) selectionIndex++;
} else {
newTextBuffer.write(newValue.text.substring(0, 2));
}
}
if (newTextLength >= 3) {
newTextBuffer.write('/' + newValue.text.substring(2, usedSubstringIndex = 3));
if (newValue.selection.end >= 2) selectionIndex++;
}
// Dump the rest.
if (newTextLength > usedSubstringIndex) newTextBuffer.write(newValue.text.substring(usedSubstringIndex, newTextLength));
return TextEditingValue(
text: newTextBuffer.toString(),
selection: TextSelection.collapsed(offset: selectionIndex),
);
}
}

最后我解决了这个问题,签出了以下代码:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class PhoneMaskFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
//Phone Mask: +X (XXX) XXX-XXXX
//While deleting character get the older value to check if you're deleting not number characters
final oldValueText = oldValue.text.replaceAll(new RegExp(r'[^0-9]'), '');
String newValueText = newValue.text;
//If its same its because you're deleting a non number value so remove the value that you want to delete
if (oldValueText == newValue.text) {
newValueText = newValueText.substring(0, newValue.selection.end - 1) + newValueText.substring(newValue.selection.end, newValueText.length);
}
final int newTextLength = newValueText.length;
int selectionIndex = newValue.selection.end;
int usedSubstringIndex = 0;
final StringBuffer newText = StringBuffer();
if (newTextLength >= 1) {
newText.write('+' + newValueText.substring(0, usedSubstringIndex = 1) + ' (');
if (newValue.selection.end >= 1) selectionIndex += 3;
}
if (newTextLength > 4) {
newText.write(newValueText.substring(1, usedSubstringIndex = 4) + ') ');
if (newValue.selection.end >= 4) selectionIndex += 2;
}
if (newTextLength > 7) {
newText.write(newValueText.substring(4, usedSubstringIndex = 7) + '-');
if (newValue.selection.end >= 7) selectionIndex++;
}
// Dump the rest.
if (newTextLength >= usedSubstringIndex) newText.write(newValueText.substring(usedSubstringIndex));
return TextEditingValue(
text: newText.toString(),
selection: TextSelection.collapsed(offset: selectionIndex),
);
}
}

最新更新