简体   繁体   English

Flutter:向文本字段中输入的用户电话号码添加连字符和括号

[英]Flutter: Adding a hyphen and brackets to a user's phone number entered in a textfield

I am trying to rearrange a user's entered phone number with brackets around the area code and a hyphen.我正在尝试重新排列用户输入的电话号码,并在区号周围加上括号和一个连字符。 For example, the user would enter 9991234567 and it would be rearranged to (999) 123-4567 inside the textfield.例如,用户输入 9991234567,它会在文本字段中重新排列为 (999) 123-4567。

I'm using a RegExp to separate the user's entry into the area code, and the 2 parts of the phone number.我正在使用 RegExp 将用户输入的区号和电话号码的两部分分开。 I am attempting to use a TextEditingController to edit the text field with brackets and a hyphen when the Save button is pressed but it does not seem to work.当按下“保存”按钮时,我试图使用 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)}';
    });
  }

This is the code for the phone number textfield.这是电话号码文本字段的代码。

  _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();
            },
          ),

You can simply use flutter_masked_text package您可以简单地使用flutter_masked_text

It's just simple as following很简单,如下

import 'package:flutter_masked_text/flutter_masked_text.dart';

class MobileNumberTextField extends StatefulWidget {
  createState() => MobileNumberTextFieldState();
}

class MobileNumberTextFieldState extends State<MobileNumberTextField> {

  final controller =MaskedTextController(mask: "(000) 000-0000");

  @override
  Widget build(BuildContext context) {

    return TextField(
      controller: controller,
      keyboardType: TextInputType.number,
      autofocus: true,
    );
  }
}

Hope it will be helpful希望它会有所帮助

I think this should do the trick.我认为这应该可以解决问题。

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))),
          ),
        ),
      ],
    );
  }
}

Hope it helps:-)希望能帮助到你:-)

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

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