Flutter Password TextField

How to Create the Password Eye in Flutter


The Full Code


import 'package:flutter/material.dart';

class PasswordTextField extends StatefulWidget {
  @override
  _PasswordTextFieldState createState() => _PasswordTextFieldState();
}

class _PasswordTextFieldState extends State {
  bool _showEye = false;
  bool _passwordIsEncrypted = true;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 250,
      child: TextFormField(
        decoration: InputDecoration(
          labelText: 'Password',
          labelStyle: TextStyle(color: Colors.white70),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.white,
              width: 2.5,
            ),
          ),
          floatingLabelBehavior: FloatingLabelBehavior.never,
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.white,
              width: 2.5,
            ),
          ),
          suffixIcon: _showEye
              ? GestureDetector(
                  child: _passwordIsEncrypted
                      ? Container(
                          width: 25,
                          height: 25,
                          padding: const EdgeInsetsDirectional.only(start: 10, end: 10),
                          alignment: Alignment.center,
                          child: Image(
                            image: AssetImage('assets/icons/visible.png'),
                            width: 25,
                          ),
                        )
                      : Container(
                          width: 25,
                          height: 25,
                          padding: const EdgeInsetsDirectional.only(start: 10, end: 10),
                          alignment: Alignment.center,
                          child: Image(
                            image: AssetImage('assets/icons/hidden.png'),
                            width: 25,
                          ),
                        ),
                  onTap: () {
                    setState(() {
                      _passwordIsEncrypted = !_passwordIsEncrypted;
                    });
                  },
                )
              : null,
        ),
        obscureText: _showEye ? _passwordIsEncrypted : true,
        onChanged: (enteredPassword) {
          _password = enteredPassword;
          if (enteredPassword.isEmpty) {
            setState(() {
              _showEye = false;
            });
          } else {
            if (!_showEye) {
              setState(() {
                _showEye = !_showEye;
              });
            }
          }
        },
        style: TextStyle(
          color: Colors.white,
        ),
      ),
    );
  }
}

No comments:

Post a Comment

| Designed by Colorlib