繁体   English   中英

Flutter 文本表单字段电话号码掩码

[英]Flutter Text Form Field Phone Number Mask

我想像这样打印写在文本表单字段中的电话号码;

xxxx-xxx-xxxx

但我想在不使用任何软件包的情况下做到这一点。 你能帮助我吗?

您可以像这样使用 obscureText: true 参数:

            const Form(
          child: TextField(
            obscureText: true,
          ),
        ),

有一个视频:在此处输入链接描述

您可以尝试使用 InputTextFormatter

class MyWidget extends StatelessWidget {
  final _mobileFormatter = PhoneNumberTextInputFormatter();
  @override
  Widget build(BuildContext context) {
    return TextFormField(
      keyboardType: TextInputType.number,
      maxLength: 13,
      inputFormatters:[
        FilteringTextInputFormatter.digitsOnly,
        _mobileFormatter,
      ],
      decoration: InputDecoration(
        icon: Icon(Icons.phone_iphone),
        hintText: "Mobile*",
      ),
    );
  }
}

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

output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM