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

时间:2019-04-23 19:58:41

标签: flutter

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

我正在使用RegExp将用户的输入分为区号和电话号码的2个部分。我试图在按下“保存”按钮时使用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();
            },
          ),

2 个答案:

答案 0 :(得分:0)

我认为这应该可以解决问题。

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

希望它会有所帮助:-)

答案 1 :(得分:0)

您可以简单地使用issue #35278软件包

这很简单

totalAmount

希望这会有所帮助