Flutter - TextField with MaskTextInputFormatter - backspace deletes all instead of 1 char
Asked Answered
C

2

10

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',
                  ),
                ),
              ),
Cords answered 30/4, 2021 at 4:22 Comment(1)
I have the same problem, have you found any solution?Penguin
T
3

add initial text to the mask like so

    final phoneFormatter = MaskTextInputFormatter(
      mask: '### ###-##-##',
      initialText: phoneNumber,
      filter: {"#": RegExp(r'[0-9]')},
    );
Tricyclic answered 16/8, 2022 at 5:45 Comment(0)
S
0

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");

 }
Sizeable answered 16/1, 2024 at 7:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.