|
| 1 | +import 'package:flutter/material.dart'; |
| 2 | + |
| 3 | +class PasswordTextField extends StatefulWidget { |
| 4 | + final TextEditingController controller; |
| 5 | + final InputDecoration decoration; |
| 6 | + final Function(String) validator; |
| 7 | + final bool enabled; |
| 8 | + final AutovalidateMode autovalidateMode; |
| 9 | + final bool autocorrect; |
| 10 | + |
| 11 | + PasswordTextField({ |
| 12 | + this.controller, |
| 13 | + this.enabled, |
| 14 | + this.validator, |
| 15 | + this.autovalidateMode, |
| 16 | + this.autocorrect = true, |
| 17 | + this.decoration, |
| 18 | + }); |
| 19 | + |
| 20 | + @override |
| 21 | + _PasswordTextFieldState createState() => _PasswordTextFieldState(); |
| 22 | +} |
| 23 | + |
| 24 | +class _PasswordTextFieldState extends State<PasswordTextField> { |
| 25 | + bool _passwordHidden; |
| 26 | + |
| 27 | + @override |
| 28 | + void initState() { |
| 29 | + super.initState(); |
| 30 | + _passwordHidden = true; |
| 31 | + } |
| 32 | + |
| 33 | + void togglePasswordVisibility() { |
| 34 | + setState(() { |
| 35 | + _passwordHidden = !_passwordHidden; |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + @override |
| 40 | + Widget build(BuildContext context) { |
| 41 | + return TextFormField( |
| 42 | + controller: widget.controller, |
| 43 | + obscureText: _passwordHidden, |
| 44 | + validator: widget.validator, |
| 45 | + autovalidateMode: widget.autovalidateMode, |
| 46 | + autocorrect: widget.autocorrect, |
| 47 | + enabled: widget.enabled, |
| 48 | + decoration: _buildDecoration(), |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + InputDecoration _buildDecoration() { |
| 53 | + var decoration; |
| 54 | + if (widget.decoration == null) { |
| 55 | + decoration = InputDecoration( |
| 56 | + suffixIcon: IconButton( |
| 57 | + icon: Icon( |
| 58 | + _passwordHidden ? Icons.visibility : Icons.visibility_off, |
| 59 | + ), |
| 60 | + onPressed: togglePasswordVisibility, |
| 61 | + ), |
| 62 | + ); |
| 63 | + } else { |
| 64 | + decoration = widget.decoration.copyWith( |
| 65 | + suffixIcon: IconButton( |
| 66 | + icon: Icon( |
| 67 | + _passwordHidden ? Icons.visibility : Icons.visibility_off, |
| 68 | + ), |
| 69 | + onPressed: togglePasswordVisibility, |
| 70 | + ), |
| 71 | + ); |
| 72 | + } |
| 73 | + return decoration; |
| 74 | + } |
| 75 | +} |
0 commit comments