Search code examples
flutterflutter-textformfieldflutter-textinputfield

How to completely hide typed characters in a Flutter TextFormField?


In my Flutter app, I use a TextFormField, so my users can enter a password.

In order to hide the characters while they are being typed, I set the obscureText property to true. But on some devices, when I type a character, that character is visible for a second or so.

Even though I know it's a very common behavior, is it possible to completely hide the character while it is being typed, and show only the obscuring character instead, aside from using a special font only made of dots?

Thanks for your help.


Solution

  • You can extend TextEditingController and override its buildTextSpan to create your own obscuring TextField:

    class ObscuringTextEditingController extends TextEditingController {
      @override
      TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) {
        return TextSpan(text: '•' * value.text.length, style: style); // Consider using a more performant way to build string, such as StringBuffer
      }
    }
    

    Please note that this is only a minimal implementation for sample purpose. You might need to be aware of other aspects from the original buildTextSpan method that may need to be implemented as well in the overriding method.


    This answer is a modified version of my answer on another question (with a different goal): https://stackoverflow.com/a/77791236/13625293