Table of Contents
What is the Point?
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:
The Complete Example
This example was recently rewritten to work adequately with Flutter 3.10.6 and beyond.
App Preview
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 Code
The full source code in main.dart (with explanations):
// main.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// show the password or not
bool _isObscure = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Kindacode.com'),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: Center(
child: TextField(
obscureText: _isObscure,
decoration: InputDecoration(
labelText: 'Password',
// this button is used to toggle the password visibility
suffixIcon: IconButton(
icon: Icon(
_isObscure ? Icons.visibility : Icons.visibility_off),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
})),
),
),
),
);
}
}
That’s it.
Conclusion
You’ve learned how to programmatically show/hide the password characters in a TextField/TextFormField. If you’d like to explore more beautiful widgets and powerful features of Flutter, take a look at the following articles:
- Flutter: Caching Network Images for Big Performance gains
- Flutter TextField: Styling labelText, hintText, and errorText
- Flutter: Creating an Auto-Resize TextField
- Flutter & SQLite: CRUD Example
- Flutter: Customizing the TextField’s Underline
- Flutter form validation example
- Flutter & Dart: Convert a String/Integer to Hex
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.