Flutter – 格式化电话号码文本字段

Luk*_*tti 8 flutter

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

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

但它不保留空格

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

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),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

anm*_*ail 8

这应该有效:

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*",
          ),
        )
Run Code Online (Sandbox Code Playgroud)

  • 您是从 https://github.com/flutter/flutter/blob/master/examples/flutter_gallery/lib/demo/material/text_form_field_demo.dart#L297-L335 获取的吗?这仅适用于美国号码 AFAIK。另外,这个例子中也存在删除问题。 (2认同)

Gen*_* Bo 7

这是一种轻量级方法(在较旧的 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
);
Run Code Online (Sandbox Code Playgroud)

就我而言,应用程序只能在国内启动,因此我不希望电话号码 UI 中出现任何国际代码。那里的所有插件似乎都期待这一点。

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

更新 1

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

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