Flutter –设置电话号码文本字段

编程入门 行业动态 更新时间:2024-10-18 03:33:38
本文介绍了Flutter –设置电话号码文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个文本字段,以正确设置电话号码的格式.我尝试使用

I am trying to make a text field that properly formats a phone number. I have tried using

NumberFormat("+# ### ### ####");

但是它不会保留空格

我试图通过在前面添加一个+来简化它,但是设置偏移量时我不能退格.

I have tried simplifying it by just adding a + to the front but I cannot backspace when I set the offset.

class PhoneInputFormatter extends TextInputFormatter { TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue) { final text = newValue.text.replaceAll(RegExp(r'\D'), ''); final offset = text.length + 1; return newValue.copyWith( text: text.length >= 1 ? '+$text' : '', selection: TextSelection.collapsed(offset: offset), ); } }

任何帮助将不胜感激

推荐答案

这应该有效:

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) + ' '); if (newValue.selection.end >= 2) selectionIndex += 1; } // Dump the rest. if (newTextLength >= usedSubstringIndex) newText.write(newValue.text.substring(usedSubstringIndex)); return new TextEditingValue( text: newText.toString(), selection: new TextSelection.collapsed(offset: selectionIndex), ); } } final _mobileFormatter = NumberTextInputFormatter(); TextFormField( keyboardType: TextInputType.phone, maxLength: 15, inputFormatters: <TextInputFormatter>[ WhitelistingTextInputFormatter.digitsOnly, _mobileFormatter, ], decoration: InputDecoration( icon: Icon(Icons.phone_iphone), hintText: "Mobile*", ), )

更多推荐

Flutter –设置电话号码文本字段

本文发布于:2023-11-24 23:24:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627326.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   电话号码   文本   Flutter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!