What's new
NoobsPlanet

Join our community today and enjoy an ad-free experience. Ask questions or learn about anything related to technology!

Show/Hide Flutter Password Field Without Library

Nikesh

Administrator
Staff member
I was working on a login screen the other day, and as usual, I wanted to add that little eye icon to let users show or hide their password. You see it in almost every app these days, and it does help users avoid typos when typing a password on mobile.
In Flutter, it turns out this is pretty straightforward. What I usually do is keep a boolean in my state, something like _obscureText = true; to track whether the password should be hidden. Then, in the TextFormField, I set obscureText: _obscureText. That part is standard.
The interesting part is adding the toggle. Flutter makes it simple because you can add a suffixIcon to your input field. I just drop an IconButton there, and its icon changes depending on _obscureText. So, when the user taps it, I call setState to flip the boolean, and Flutter updates the UI automatically.
Here's basically what the code looks like, without overcomplicating it:

Code:
TextFormField(
obscureText: _obscureText,
decoration: InputDecoration(
labelText: 'Password',
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
),
onPressed: () {
setState(() {
_obscureText = !_obscureText;
      });
    },
   ),
),
)
That's really it. Nothing fancy, but it works well. I've used this in multiple apps, and users find it handy. It feels like one of those small details that make your app look more professional and easier to use.
I thought I'd write this down because I remember the first time I had to do it, I assumed it would be more complicated. But it turned out to be just a few lines of code and a simple toggle.
Full Source Code:

Code:
class PasswordField extends StatefulWidget {
@override
_PasswordFieldState createState() => _PasswordFieldState();
}
class _PasswordFieldState extends State<PasswordField> {
bool _obscureText = true;
@override
Widget build(BuildContext context) {
return TextFormField(
obscureText: _obscureText,
decoration: InputDecoration(
labelText: 'Password',
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
),
onPressed: () {
setState(() {
_obscureText = !_obscureText;
        });
      },
     ),
    ),
   );
}
}
If you're building your own login or signup form, give it a try. It's one of those small features that users appreciate more than we think.
 
Top