How to Create Text Input for Password in Flutter

The importance of passwords is inexplainable. That’s the reason when entering the password the text should not be visible for better safety and security. In this Flutter tutorial, let’s see how to create a Text Input to enter a password in Flutter.

I already have a blog post on how to create a Text Input in Flutter. Like I mentioned in that blog post, we use the TextField widget to create inputs in Flutter.

The TextField widget has so many useful properties. The property obscureText can be used to hide the text which is being edited. You just need to set obscureText true.

TextField(
          obscureText: true,
        ),

Following is the complete example of Flutter TextField for password entry.

import 'package:flutter/material.dart';


class PasswordExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Text Input Password Example',
      home: MyInput(),
    );
  }
}

// Define a custom Form widget.
class MyInput extends StatefulWidget {
  @override
  _MyInputState createState() => _MyInputState();
}

// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyInputState extends State<MyInput> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Password Text Input Tutorial'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(child: Column(children: <Widget>[TextField(
          obscureText: true,
          controller: myController,
        ),
        RaisedButton(
          child: Text('Retrieve Text'),
          onPressed: (){
            return showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // Retrieve the text the that user has entered by using the
                // TextEditingController.
                content: Text(myController.text),
              );
            },
          );
          },
        ),]
      ),
      ),
      ),   
    );
  }
}

As you see, in the example I also have a controller so that when the button is pressed the entered password is shown as Alert Dialog.

Following is the output of the Flutter example.

flutter password field example

Thank you for reading!

Leave a Comment

Your email address will not be published. Required fields are marked *