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
When Using TextEditingController. TextEditingController myController = TextEditingController()..text = 'Your initial value'; TextField( controller: myController ... )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With