Reputation: 190
I am trying to learn how to use the TextField properly with the MaskTextInputFormatter. I am also using a controller to set a initial value to it. But when the user presses the backspace on it all the text is deleted instead of only 1 char.
Does someone have any ideia of how setting it correctly? I have also tried to change the "selection" property through the controller but nothing changed.
Stateful:
// This sets the initial text into the TextField
class _ErrosState extends State<Erros>
{
var valorController = TextEditingController(
text: "(91) 12345-1234");
// __________________________________________________
// StateLess
class CadastroTelefonePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body:
TextField(
controller: _ErrosState().valorController,
inputFormatters: [MaskTextInputFormatter(
mask: '(##) #####-####',
filter: {"#": RegExp(r'[0-9 ]')})
],
onChanged: (text) {
_ErrosState.input = text;
},
obscureText: false,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: '(XX) XXXXX-XXXX',
),
),
),
Upvotes: 10
Views: 1836
Reputation: 101
You need to update the value for mask , then set the value for TextField using controller.text. Try this code:
final _maskFormatter = MaskTextInputFormatter(
mask: '(###) ### - ####', filter: {"#": RegExp(r'[0-9]')});
final TextEditingController _phoneController = TextEditingController();
TextFormField(
keyboardType: TextInputType.number,
controller: _phoneController,
inputFormatters: [_maskFormatter],
)
onTap: () {
_maskFormatter.updateMask(
mask: '(###) ### - ####',
filter: {"#": RegExp(r'[0-9]')},
newValue: TextEditingValue(
text: listNameSearch[index]
.customerPhone ??
""));
_phoneController.text = StringHelper
.convertUsPhoneNumber(
listNameSearch[index]
.customerPhone ??
"N/A");
}
Upvotes: 0
Reputation: 49
add initial text to the mask like so
final phoneFormatter = MaskTextInputFormatter(
mask: '### ###-##-##',
initialText: phoneNumber,
filter: {"#": RegExp(r'[0-9]')},
);
Upvotes: 3