Flutter 颤振:向用户添加连字符和方括号';s在文本字段中输入的电话号码

Flutter 颤振:向用户添加连字符和方括号';s在文本字段中输入的电话号码,flutter,Flutter,我正试图用括号和连字符重新排列用户输入的电话号码。例如,用户将输入9991234567,然后在文本字段中将其重新排列为(999)123-4567 我使用RegExp将用户输入的区号和电话号码的两部分分开。当按下保存按钮时,我试图使用TextEditingController编辑带有括号和连字符的文本字段,但它似乎不起作用 _saveButtonPressed() async { RegExp phone = RegExp(r'(\d{3})(\d{3})(\d{4})'); va

我正试图用括号和连字符重新排列用户输入的电话号码。例如,用户将输入9991234567,然后在文本字段中将其重新排列为(999)123-4567

我使用RegExp将用户输入的区号和电话号码的两部分分开。当按下保存按钮时,我试图使用TextEditingController编辑带有括号和连字符的文本字段,但它似乎不起作用

_saveButtonPressed() async {
    RegExp phone = RegExp(r'(\d{3})(\d{3})(\d{4})');
    var matches = phone.allMatches(UserProfile.instance.phone);
    var match = matches.elementAt(0);
    setState(() {
      phoneController.text = '(${match.group(1)}) ${match.group(2)}-${match.group(3)}';
    });
  }
这是电话号码文本字段的代码

  _makeRowForAttribute(
            imageAsset: "assets/images/phone.png",
            title: "PHONE NUMBER",
            keyboardType: TextInputType.phone,
            placeholder: "6131110123",
            charLimit: 10,
            initialValue: UserProfile.instance.phone,
            controller: phoneController,
            onSave: (phone) {
              UserProfile.instance.phone = phone.toString();
            },
          ),

我认为这应该能奏效

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

class FormattedPhoneNumber extends StatefulWidget {
  @override
  _FormattedPhoneNumberState createState() => _FormattedPhoneNumberState();
}

class _FormattedPhoneNumberState extends State<FormattedPhoneNumber> {
  String text = "";

  convert(TextEditingValue oldValue, TextEditingValue newValue) {
    print("OldValue: ${oldValue.text}, NewValue: ${newValue.text}");
    String newText = newValue.text;

    if (newText.length == 10) {
      // The below code gives a range error if not 10.
      RegExp phone = RegExp(r'(\d{3})(\d{3})(\d{4})');
      var matches = phone.allMatches(newValue.text);
      var match = matches.elementAt(0);
      newText = '(${match.group(1)}) ${match.group(2)}-${match.group(3)}';
    }

    // TODO limit text to the length of a formatted phone number?

    setState(() {
      text = newText;
    });

    return TextEditingValue(
        text: newText,
        selection: TextSelection(
            baseOffset: newValue.text.length,
            extentOffset: newValue.text.length));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            inputFormatters: [
              TextInputFormatter.withFunction(
                  (oldValue, newValue) => convert(oldValue, newValue)),
            ],
            keyboardType: TextInputType.phone,
            decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: "input",
                labelText: "Converts to phone number format"),

            // Fixes a problem with text-caret only being at the start of the textfield.
            controller: TextEditingController.fromValue(new TextEditingValue(
                text: text,
                selection: new TextSelection.collapsed(offset: text.length))),
          ),
        ),
      ],
    );
  }
}
导入“包装:颤振/材料.省道”;
导入“包:flifter/services.dart”;
类FormattedPhoneNumber扩展StatefulWidget{
@凌驾
_FormattedPhoneNumberState createState()=>_FormattedPhoneNumberState();
}
类_FormattedPhoneNumberState扩展状态{
字符串文本=”;
转换(TextEditingValue旧值、TextEditingValue新值){
打印(“OldValue:${OldValue.text},NewValue:${NewValue.text}”);
字符串newText=newValue.text;
如果(newText.length==10){
//如果不是10,下面的代码给出一个范围错误。
RegExp phone=RegExp(r'(\d{3})(\d{3})(\d{4});
var matches=phone.allMatches(newValue.text);
var match=matches.elementAt(0);
newText='(${match.group(1)})${match.group(2)}-${match.group(3)}';
}
//TODO是否将文本长度限制为格式化电话号码的长度?
设置状态(){
文本=新文本;
});
返回TextEditingValue(
文本:新文本,
选择:文本选择(
baseOffset:newValue.text.length,
extendtoffset:newValue.text.length);
}
@凌驾
小部件构建(构建上下文){
返回列(
mainAxisAlignment:mainAxisAlignment.center,
crossAxisAlignment:crossAxisAlignment.center,
儿童:[
填充物(
填充:常数边集全部(8.0),
孩子:TextField(
输入格式化程序:[
TextInputFormatter.withFunction(
(oldValue,newValue)=>convert(oldValue,newValue)),
],
键盘类型:TextInputType.phone,
装饰:输入装饰(
边框:OutlineInputBorder(),
hintText:“输入”,
labelText:“转换为电话号码格式”),
//修复了文本插入符号仅位于文本字段开头的问题。
控制器:TextEditingController.fromValue(新的TextEditingValue(
文本:文本,
选择:新建文本选择。折叠(偏移量:text.length)),
),
),
],
);
}
}
希望对您有所帮助:-)

您只需使用该软件包即可

简单如下

import'package:flatter_masked_text/flatter_masked_text.dart';
类MobileNumberTextField扩展StatefulWidget{
createState()=>MobileNumberTextFieldState();
}
类MobileNumberTextFieldState扩展了状态{
最终控制器=掩码特写控制器(掩码:“(000)000-0000”);
@凌驾
小部件构建(构建上下文){
返回文本字段(
控制器:控制器,
键盘类型:TextInputType.number,
自动对焦:对,
);
}
}

希望这会有所帮助

当使用硬编码字符串进行测试时,您的RegExp似乎正在工作。你可以看看我今天早些时候回答的这个问题,这个问题可能与你的问题有关:谢谢。是的,看来我的RegExp正在工作。但是,我认为我使用控制器时有问题。请尝试使用InputFormatter:
TextField(inputFormatters:[WhiteListingTestExputFormatter(RegExp)(\d{3})(\d{3})(\d{4})),]
您建议我在哪里尝试InputFormatter抱歉?我在哪里设置了状态?不幸的是,当我尝试将此代码集成到我的代码中时,我没有检测到用户输入的号码有任何更改。