0.3 C
New York
Thursday, November 30, 2023

Flutter: Show/Hide Password in TextField/TextFormField

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

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

Screenshot:Advertisements

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

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

Screenshot:

The Complete Example

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 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;
                      });
                    })),
          ),
        ),
      ),
    );
  }
}

AdvertisementsThatÂ’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:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles