Flutter: Show/Hide Password in TextField/TextFormField

Last updated on November 20, 2020 A Goodman Loading... 2 comments

To hide an entered password in a TextField/TextFormField, just set its obscureText property to true:

TextField(
   obscureText: true,
   /* ... */
),

Screenshot:

To show the entered password for the user to read it, set obscureText to false:

TextField(
   obscureText: false,
   /* ... */
),

Screenshot:

A Complete Example

We’ll make a simple Flutter app that contains a TextField widget (you can use TextFormField as well) at the center of the screen. This text field lets the user type a password in and has an eye-icon button to show/hide the entered password. Here’s how it works:

The full code:

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isObscure = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Center(
          child: TextField(
            obscureText: _isObscure,
            decoration: InputDecoration(
                labelText: 'Password',
                suffixIcon: IconButton(
                    icon: Icon(
                        _isObscure ? Icons.visibility : Icons.visibility_off),
                    onPressed: () {
                      setState(() {
                        _isObscure = !_isObscure;
                      });
                    })),
          ),
        ),
      ),
    );
  }
}

That’s it. Happy Fluttering 🙂

Related Articles

guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Frank
Frank
1 month ago

Nice example

2
0
Would love your thoughts, please comment.x
()
x