Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter – formatting phone number text field

Tags:

flutter

I am trying to make a text field that properly formats a phone number. I have tried using

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

But it doesn't retain spaces

I have tried simplifying it by just adding a + to the front but I cannot backspace when I set the offset.

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

Any help would be appreciated

like image 719
Luke Pighetti Avatar asked Oct 12 '18 13:10

Luke Pighetti


People also ask

How do you give a text field value in Flutter?

When Using TextEditingController. TextEditingController myController = TextEditingController()..text = 'Your initial value'; TextField( controller: myController ... )


1 Answers

Here's a light weight approach (does not work correctly on older Android OS KitKit) where you can set the specific format you want with the MaskedInputFormater class, using the plugin: flutter_multi_formatter

import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

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

In my case, app is only domestic to start, so I don't want any international code in the phone number UI. All the plugins out there seem to expect that.

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

Update 1

Just tested this on the older Android KitKat, and unfortunately doesn't work correctly there.

However, depending on the app and the audience - if you know most users will have a later OS, this is not a bad solution for getting something out there.

like image 158
Gene Bo Avatar answered Oct 15 '22 05:10

Gene Bo