【问题标题】:Flutter – formatting phone number text fieldFlutter – 格式化电话号码文本字段
【发布时间】:2018-10-12 13:21:01
【问题描述】:

我正在尝试创建一个正确格式化电话号码的文本字段。我试过使用

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

但它不保留空格

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

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

任何帮助将不胜感激

【问题讨论】:

标签: flutter


【解决方案1】:

这应该工作:

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*",
          ),
        )

【讨论】:

  • 你是从github.com/flutter/flutter/blob/master/examples/flutter_gallery/… 那里得到的吗?这仅适用于美国号码 AFAIK。另外,这个例子中也存在删除问题。
  • 你想要什么格式.?上面的代码给出 - ### ### ####
  • E.164国际电话
  • 更新了支持 E.164 格式的答案:+442071838750
  • 我希望格式是这样的@anmol.majhail:+7 923 777 77 77+91 090090909这是当前结果
【解决方案2】:

这是一种轻量级的方法(在较旧的 Android OS KitKit 上无法正常工作),您可以使用 MaskedInputFormater 类设置所需的特定格式,使用插件:flutter_multi_formatter

import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

TextFormField(
  keyboardType: TextInputType.phone,
  autocorrect: false,
  inputFormatters: [
    MaskedInputFormater('(###) ###-####')
  ],
  // .. etc
);

在我的情况下,应用程序只能在国内启动,所以我不希望电话号码 UI 中有任何国际代码。那里的所有插件似乎都期待这一点。

==========================

更新 1

刚刚在较旧的 Android KitKat 上进行了测试,不幸的是在那里无法正常工作。

但是,取决于应用程序和受众 - 如果您知道大多数用户将拥有更新版本的操作系统,那么这对于获得一些东西来说并不是一个糟糕的解决方案。

【讨论】:

    【解决方案3】:

    使用来自pub.devintl_phone_number_input 包。我认为这很容易。 关注this link

    【讨论】:

      【解决方案4】:

      RU 编号的解决方案。 我们有相同的数字,但写法不同。 8900.. = +7900.. 另外,如果我们从 9 开始输入,它会自动变成 9.. > +79..

      因此,此代码结果将是:+7(900)000-00-00

      import 'package:flutter/material.dart';
      import 'package:flutter/services.dart';
      
      class NumberTextInputFormatter extends TextInputFormatter {
        @override
        TextEditingValue formatEditUpdate(
            TextEditingValue oldValue, TextEditingValue newValue) {
          final newTextLength = newValue.text.length;
          int selectionIndex = newValue.selection.end;
          int usedSubstringIndex = 1;
          final newTextBuffer = StringBuffer();
      
      if (newTextLength >= 1) {
        if (newValue.text.startsWith(RegExp(r'[789]'))) {
          newTextBuffer.write('+7');
          if (newValue.text.startsWith('9')) {
            newTextBuffer.write('(9');
            selectionIndex = 4;
          }
          if (newValue.selection.end >= 1) selectionIndex++;
        }
      }
      
      if (newTextLength >= 2) {
        newTextBuffer
            .write('(' + newValue.text.substring(1, usedSubstringIndex = 2));
        if (newValue.selection.end >= 2) selectionIndex++;
      }
      if (newTextLength >= 5) {
        newTextBuffer.write(
            newValue.text.substring(usedSubstringIndex, usedSubstringIndex = 4) +
                ')');
        if (newValue.selection.end >= 4) selectionIndex++;
      }
      if (newTextLength >= 8) {
        newTextBuffer.write(
            newValue.text.substring(usedSubstringIndex, usedSubstringIndex = 7) +
                '-');
        if (newValue.selection.end >= 7) selectionIndex++;
      }
      if (newTextLength >= 10) {
        newTextBuffer.write(
            newValue.text.substring(usedSubstringIndex, usedSubstringIndex = 9) +
                '-');
        if (newValue.selection.end >= 9) selectionIndex++;
      }
      
      // Dump the rest.
      if (newTextLength > usedSubstringIndex) newTextBuffer.write(newValue.text.substring(usedSubstringIndex, newTextLength));
      
      return TextEditingValue(
        text: newTextBuffer.toString(),
        selection: TextSelection.collapsed(offset: selectionIndex),
      );
      
      
      }
      
      }
      

      【讨论】:

        【解决方案5】:

        (仅限美国,但易于修改)我建议仅在模型中存储数字并专门为视图格式化数字。为此,我做了以下工作:

        /// Human readable version of the phone number
        String getFormattedPhoneNumber() {
          if (_phoneNumber.isEmpty) {
            return "";
          }
        
          String phoneNumber = _phoneNumber;
          bool addPlus = phoneNumber.startsWith("1");
          if (addPlus) phoneNumber = phoneNumber.substring(1);
          bool addParents = phoneNumber.length >= 3;
          bool addDash = phoneNumber.length >= 8;
        
          // +1
          String updatedNumber = "";
          if (addPlus) updatedNumber += "+1";
        
          // (222)
          if (addParents) {
            updatedNumber += "(";
            updatedNumber += phoneNumber.substring(0, 3);
            updatedNumber += ")";
          } else {
            updatedNumber += phoneNumber.substring(0);
            return updatedNumber;
          }
        
          // 111
          if (addDash) {
            updatedNumber += phoneNumber.substring(3, 6);
            updatedNumber += "-";
          } else {
            updatedNumber += phoneNumber.substring(3);
            return updatedNumber;
          }
        
          // 3333
          updatedNumber += phoneNumber.substring(6);
          return updatedNumber;
        }
        

        在你的 TextInput onChanged 方法中:

        void setPhoneNumber(String phoneNumber) {
          if (phoneNumber.contains("\(") && !phoneNumber.contains("\)")) {
            // Remove the digit the user wanted to remove but couldn't b/c a paren
            // was in the way.
            phoneNumber = phoneNumber.substring(0, phoneNumber.length - 1);
          }
        
          // Only store the actual digits
          phoneNumber = phoneNumber.replaceAll(RegExp("[^0-9]"), "");
        
          // Don't let the user enter more digits than is possible
          int maxLength = phoneNumber.startsWith("1") ? 11 : 10;
          if (phoneNumber.length > maxLength) {
            phoneNumber = phoneNumber.substring(0, maxLength);
          }
        
          model.setPhoneNumber(phoneNumber);
          
          // Notify the UI to update based on new input
          notifyListeners();
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-05
          • 1970-01-01
          • 2013-12-07
          相关资源
          最近更新 更多