【问题标题】:How to format mobile number based on country code in flutter如何在flutter中根据国家代码格式化手机号码
【发布时间】:2020-01-03 15:20:00
【问题描述】:

谁能告诉我如何根据国家代码格式化手机号码。希望你能理解。

这是我到目前为止所做的尝试:

var controller = new MaskedTextController(mask: '(000) 000 0000');

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar( title: Text("Masked Text"), ),
    body: Container(
       child: Row(
          children: <Widget>[
             Expanded(
               child: TextField(
                  controller: controller,
                  keyboardType: TextInputType.number, maxLength: 18,
               ),
             ),
          ],
       )),
   ); 
 }

【问题讨论】:

  • 显示到目前为止您尝试了什么的代码在哪里?
  • var controller = new MaskedTextController(mask: '(000) 000 0000'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Masked Text"), ), body: Container( child: Row( children: [ Expanded( child: TextField( controller:控制器,键盘类型:TextInputType.number,最大长度:18,),),],)),); }
  • 我已经完成了这个,只是尝试格式化数字。我不知道如何根据国家代码来做。希望你能理解:)请帮助我。
  • @MazinIbrahim 你能帮我解决这个问题吗?
  • 请耐心等待!让我想想办法。

标签: flutter flutter-dependencies numberformatter mobile-country-code


【解决方案1】:

flutter 图库应用程序Text Form fields 代码的最后一个类(_UsNumberTextInputFormatter)对你有很大帮助。

关键是为TextFormField定义一个inputFormatters。

 

    class _NumberFormatterDemo extends State {
      final List _allActivities = ['+1', '+91'];
      String _activity = '+1';
      _NumberTextInputFormatter _phoneNumberFormatter =
          _NumberTextInputFormatter(1);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: const Text('Number Formatter Demo'),
            ),
            body: DropdownButtonHideUnderline(
              child: SafeArea(
                top: false,
                bottom: false,
                child: ListView(
                    padding: const EdgeInsets.all(16.0),
                    children: [
                      const SizedBox(height: 8.0),
                      InputDecorator(
                        decoration: const InputDecoration(
                          labelText: 'Country Code',
                          hintText: 'Select a country code',
                          contentPadding: EdgeInsets.zero,
                        ),
                        isEmpty: _activity == null,
                        child: DropdownButton(
                          value: _activity,
                          onChanged: (String newValue) {
                            setState(() {
                              _activity = newValue;
                              switch(newValue){
                                case '+1':
                                  _phoneNumberFormatter = _NumberTextInputFormatter(1);
                                  break;
                                case '+91':
                                  _phoneNumberFormatter = _NumberTextInputFormatter(91);
                                  break;
                              }
                            });
                          },
                          items: _allActivities
                              .map>((String value) {
                            return DropdownMenuItem(
                              value: value,
                              child: Text(value),
                            );
                          }).toList(),
                        ),
                      ),
                      const SizedBox(height: 24.0),
                      TextFormField(
                        decoration: const InputDecoration(
                          border: UnderlineInputBorder(),
                          filled: true,
                          icon: Icon(Icons.phone),
                          hintText: 'Where can we reach you?',
                          labelText: 'Phone Number *',
                        ),
                        keyboardType: TextInputType.phone,
                        onSaved: (String value) {},
                        inputFormatters: [
                          WhitelistingTextInputFormatter.digitsOnly,
                          // Fit the validating format.
                          _phoneNumberFormatter,
                        ],
                      ),
                    ]),
              ),
            ));
      }
    }

    class _NumberTextInputFormatter extends TextInputFormatter {
      int _whichNumber;
      _NumberTextInputFormatter(this._whichNumber);

      @override
      TextEditingValue formatEditUpdate(
        TextEditingValue oldValue,
        TextEditingValue newValue,
      ) {
        final int newTextLength = newValue.text.length;
        int selectionIndex = newValue.selection.end;
        int usedSubstringIndex = 0;
        final StringBuffer newText = StringBuffer();
        switch (_whichNumber) {
          case 1:
            {
              if (newTextLength >= 1 ) {
                newText.write('(');
                if (newValue.selection.end >= 1) selectionIndex++;
              }
              if (newTextLength >= 4 ) {
                newText.write(
                    newValue.text.substring(0, usedSubstringIndex = 3) + ') ');
                if (newValue.selection.end >= 3) selectionIndex += 2;
              }
              if (newTextLength >= 7 ) {
                newText.write(
                    newValue.text.substring(3, usedSubstringIndex = 6) + '-');
                if (newValue.selection.end >= 6) selectionIndex++;
              }
              if (newTextLength >= 11 ) {
                newText.write(
                    newValue.text.substring(6, usedSubstringIndex = 10) + ' ');
                if (newValue.selection.end >= 10) selectionIndex++;
              }
              break;
            }
          case 91:
            {
              if (newTextLength >= 5) {
                newText.write(
                    newValue.text.substring(0, usedSubstringIndex = 5) + ' ');
                if (newValue.selection.end >= 6) selectionIndex++;
              }
              break;
            }
        }
        // Dump the rest.
        if (newTextLength >= usedSubstringIndex)
          newText.write(newValue.text.substring(usedSubstringIndex));
        return TextEditingValue(
          text: newText.toString(),
          selection: TextSelection.collapsed(offset: selectionIndex),
        );
      }
    }

 

这是我的工作示例 -

【讨论】:

  • 非常感谢您的帮助。它有一些小错误,我修复了它们。 :)
【解决方案2】:

您可以使用以下电话号码格式化程序:

此格式化程序将 00000000 转换为 (000) 000 0000

class PhoneNumberFormatter extends TextInputFormatter {
  PhoneNumberFormatter();

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    
    if (!oldValue.text.contains("(") &&
        oldValue.text.length >= 10 &&
        newValue.text.length != oldValue.text.length) {
      return TextEditingValue(
        text: "",
        selection: TextSelection.collapsed(offset: 0),
      );
    }

    if(oldValue.text.length>newValue.text.length){
      return TextEditingValue(
        text: newValue.text.toString(),
        selection: TextSelection.collapsed(offset: newValue.text.length),
      );
    }

    var newText = newValue.text;
    if (newText.length == 1) newText ="(" + newText;
    if (newText.length == 4) newText = newText + ") ";
    if (newText.length == 9) newText = newText + " ";

    return TextEditingValue(
      text: newText.toString(),
      selection: TextSelection.collapsed(offset: newText.length),
    );
  }
}

欲了解更多信息:https://www.codesenior.com/en/tutorial/Flutter-Phone-Number-Formatter

【讨论】:

    【解决方案3】:

    一个好的和简单的解决方案是https://pub.dev/packages/intl_phone_number_input

      final TextEditingController controller = TextEditingController();
      String initialCountry = 'NG';
      PhoneNumber number = PhoneNumber(isoCode: 'NG');
    
      InternationalPhoneNumberInput(
                  onInputChanged: (PhoneNumber number) {
                    print(number.phoneNumber);
                  },
                  onInputValidated: (bool value) {
                    print(value);
                  },
                  selectorConfig: SelectorConfig(
                    selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
                    backgroundColor: Colors.black,
                  ),
                  ignoreBlank: false,
                  autoValidateMode: AutovalidateMode.disabled,
                  selectorTextStyle: TextStyle(color: Colors.black),
                  initialValue: number,
                  textFieldController: controller,
                  inputBorder: OutlineInputBorder(),
                ),
    

    【讨论】:

      猜你喜欢
      • 2013-11-02
      • 2013-12-01
      • 2021-09-07
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多