Open In App

Flutter – Make a Toggle Password Visibility Button

Last Updated : 19 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to create a button when pressed, displays the password entered in the obscured text field in Flutter. In this we are going to take a boolean variable named as showPassword, If showPassword is true, the password is displayed in plain text, otherwise, it is obscured. In this article, we are going to Create an obscured TextField to enter the password, and then create a button to toggle the visibility of the Password. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




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


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Define the app's theme
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false, // Hide the debug banner
      home: PasswordTextField(), // Set the home screen to PasswordTextField
    );
  }
}


Step 5: Create PasswordTextField Class

In this class we are going to implement the button that toggle the visibility of the obscured password. This class contains a boolean varriable named as showPassword and a method named as toggleShowPassword function is called when the button is pressed. It toggles the value of showPassword.The TextField widget now uses the obscureText property, which is controlled by the showPassword variable. If showPassword is true, the password is displayed in the textView; otherwise, it is obscured.

 void toggleShowPassword() {
setState(() {
showPassword = !showPassword; // Toggle the showPassword flag
});
}

Dart




class PasswordTextField extends StatefulWidget {
  @override
  _PasswordTextFieldState createState() => _PasswordTextFieldState();
}
  
class _PasswordTextFieldState extends State<PasswordTextField> {
  String password = ''; // Initialize the password variable
  bool showPassword = false; // Initialize the showPassword flag
  
  void toggleShowPassword() {
    setState(() {
      showPassword = !showPassword; // Toggle the showPassword flag
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Password TextField Example'), // Set the app bar title
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: Column(
            children: <Widget>[
              TextField(
                obscureText: !showPassword, // Toggle password visibility
                decoration: InputDecoration(
                  labelText: 'Password',
                  hintText: 'Enter your password',
                ),
                onChanged: (value) {
                  setState(() {
                    password = value; // Update the password when input changes
                  });
                },
              ),
              SizedBox(height: 10.0), // Add spacing
              ElevatedButton(
                // Call toggleShowPassword when pressed
                onPressed: toggleShowPassword, 
                  
                // Change button label based on showPassword flag
                child: Text(showPassword ? 'Hide Password' : 'Show Password'), 
              ),
              SizedBox(height: 10.0), // Add spacing
              Text(
                // Display the password or asterisks based on showPassword
                'Password: ${showPassword ? password : '******'}'
                // Apply text style
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Define the app's theme
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false, // Hide the debug banner
      home: PasswordTextField(), // Set the home screen to PasswordTextField
    );
  }
}
  
class PasswordTextField extends StatefulWidget {
  @override
  _PasswordTextFieldState createState() => _PasswordTextFieldState();
}
  
class _PasswordTextFieldState extends State<PasswordTextField> {
  String password = ''; // Initialize the password variable
  bool showPassword = false; // Initialize the showPassword flag
  
  void toggleShowPassword() {
    setState(() {
      showPassword = !showPassword; // Toggle the showPassword flag
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Password TextField Example'), // Set the app bar title
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: Column(
            children: <Widget>[
              TextField(
                obscureText: !showPassword, // Toggle password visibility
                decoration: InputDecoration(
                  labelText: 'Password',
                  hintText: 'Enter your password',
                ),
                onChanged: (value) {
                  setState(() {
                    password = value; // Update the password when input changes
                  });
                },
              ),
              SizedBox(height: 10.0), // Add spacing
              ElevatedButton(
                // Call toggleShowPassword when pressed
                onPressed: toggleShowPassword, 
                  
                // Change button label based on showPassword flag
                child: Text(showPassword ? 'Hide Password' : 'Show Password'), 
              ),
              SizedBox(height: 10.0), // Add spacing
              Text(
                // Display the password or asterisks based on showPassword
                'Password: ${showPassword ? password : '******'}'
                // Apply text style
                style: TextStyle(fontWeight: FontWeight.bold), 
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads