0

tengo un TextFormField y me gustaría saber si se puede dejar fijo el número 3 al inicio y que no pueda borrarse para que el usuario siga digitando los demás números, gracias.

1 respuesta 1

2

Sí es posible, primero podrías definir tu TextEditingController con el valor inicial que podría ser 3.

final controller = TextEditingController(text: '3');

Luego le asignas al TextField así:

              TextField(
                    controller: controller,
                    inputFormatters: [MyCustomInputFormatter()],
                  )

En inputFormatters he creado uno personalizado que se llama MyCustomInputFormatter y este sería su implementación:


class MyCustomInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    const firstNumber = '3';
    if (newValue.text.startsWith(firstNumber)) {
      return newValue;
    }
    return newValue.copyWith(
      text: '$firstNumber${newValue.text}',
      selection: TextSelection.fromPosition(
        TextPosition(offset: newValue.text.length + 1),
      ),
    );
  }
}

Espero te sirva.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.