首页 > 解决方案 > 美国电话号码 E.164 的 Flutter TextInputFormatter 不起作用。如何使用美国 (+1) 代码进行格式化

问题描述

我正在尝试使用 Firebase Phone Auth 进行用户登录,但没有成功。我尝试添加不同的 TextInputFormatter 变体并继续收到 firebase 错误“格式不正确,E.164”。

class NumberTextInputFormatter 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 >= 1) {
      newText.write('+');
      if (newValue.selection.end >= 1) selectionIndex++;
    }
    if (newTextLength >= 3) {
      newText.write(newValue.text.substring(0, usedSubstringIndex = 2) + '1');
      if (newValue.selection.end >= 2) selectionIndex += 1;
    }
    if (newTextLength >= usedSubstringIndex) newText.write(newValue.text.substring(usedSubstringIndex));
    return new TextEditingValue(
      text: newText.toString(),
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}

final _uscodeformatter = NumberTextInputFormatter();

我是 Flutter 的新手,没有看到任何有关这方面的指导文档。当前的 TextInputFormatter 返回+40 43107231而不是+14043107231. 我尝试过使用条件语句,例如

if (newTextLength >= 10) {
      newText.write('1');
      if (newValue.selection.end >= 10) selectionIndex++;
    }

标签: flutterdart

解决方案


推荐阅读