skip to Main Content

I’ve made a TextField that is suppose to update the user’s info.

The user has to type either 11 or 14 numbers, so the mask for the textfield has to change if someone types more than 11 numbers. How do I do that?

Masks:

var mascaraCpf = MaskTextInputFormatter(
      mask: '###.###.###-##',
      filter: {"#": RegExp(r'[0-9]')},
      type: MaskAutoCompletionType.lazy);

  var mascaraCnpj = MaskTextInputFormatter(
      mask: '##.###.###/####-##',
      filter: {"#": RegExp(r'[0-9]')},
      type: MaskAutoCompletionType.lazy);

TextField:

TextField(
   keyboardType: TextInputType.number,
   inputFormatters: [
     mascaraCpf,
     FilteringTextInputFormatter.digitsOnly
   ],
      controller: cpfController,
      decoration: InputDecoration(
      filled: true,
      fillColor: Color(0xffFCF9F4),
      border: OutlineInputBorder(
            borderRadius:                                  
            BorderRadius.all(Radius.circular(5))),
            hintText: appModel.usuario!.cpf,
         ),
       ),

2

Answers


  1. Do you have an StatefulWidget?

    If yes, try something like the following:

    onChanged: (value) {
      if (value.length >= 11) {
        setState(() {
          //change something
        });
      } else {
        setState(() {
          //change back
        });
      }
    }
    
    Login or Signup to reply.
  2. First, make sure your screen is a stateful widget.

    Then replace the textfield with the following code:

    TextField(
                onChanged: (value) => {
                  if (value.length >= 11 && value.length <= 14)    //changing value if input length is more than 11 and less than 14
                    {
                      setState(() {
                        currentMask = mascaraCnpj;
                      })
                    }
                  else                            
                    {
                      if(currentMask != mascaraCpf) {  //rebuilding screen if  currentMask != mascaraCpf , otherwise it'll lead to unnecessary rebuilds
                         setState(() {
                        currentMask = mascaraCpf;
                      })
                      }
                    }
                },
                keyboardType: TextInputType.number,
                inputFormatters: [currentMask, FilteringTextInputFormatter.digitsOnly],
                controller: TextEditingController(),
                decoration: InputDecoration(
                  filled: true,
                  fillColor: Color(0xffFCF9F4),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(5))),
                  hintText: appModel.usuario!.cpf,
                ),
              ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search