Home > Back-end >  How to show and hide password in TextFormField?
How to show and hide password in TextFormField?

Time:11-21

I want to add eye to password field in flutter project

this is my code:

TextFormField(
        decoration: const InputDecoration(
          label: Text('PASSWORD'),
        ),
        keyboardType: TextInputType.visiblePassword,
        obscureText: true,
        validator: (val) {
          if (val!.length < 6) {
            return "Please enter at least 6 characters";
          }
          return null;
        },
        onSaved: (val) => data['password'] = val!,
      ),

CodePudding user response:

You can use this custom widget:

class CustomInput extends StatefulWidget {
  final String? label;
  final TextInputType? keyboardType;
  final String? Function(String?)? validator;
  final Function(String?)? onSaved;
  final bool obscureText;
  const CustomInput(
      {Key? key,
      this.label,
      this.keyboardType,
      this.validator,
      this.onSaved,
      this.obscureText = false})
      : super(key: key);

  @override
  State<CustomInput> createState() => _CustomInputState();
}

class _CustomInputState extends State<CustomInput> {
  bool showPassword = false;
  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
          label: Text(widget.label ?? ''),
          suffixIcon: InkWell(
            onTap: () {
              setState(() {
                showPassword = !showPassword;
              });
            },
            child: Icon(showPassword
                ? Icons.remove_red_eye
                : Icons.remove_red_eye_outlined),
          )),
      keyboardType: widget.keyboardType,
      obscureText: showPassword ? false : widget.obscureText,
      validator: widget.validator,
      onSaved: widget.onSaved,
    );
  }
}

and use it like this:

CustomInput(
          label: 'PASSWORD',
          keyboardType: TextInputType.visiblePassword,
          onSaved: (val) => data['password'] = val!,
          validator: (val) {
            if (val!.length < 6) {
              return "Please enter at least 6 characters";
            }
            return null;
          },
          obscureText: true,
)

enter image description here

CodePudding user response:

Add a suffixIcon in the decoration part :

decoration: InputDecoration(
        suffixIcon: IconButton(
          onPressed: showHideText(),
          icon: Icon(Icons.yourIcon),
          ),
),
  • Related