How to show/hide password in TextFormField?

前端 未结 9 1437
故里飘歌
故里飘歌 2021-02-01 00:54

Currently I have my password TextFormField like this:

TextFormField(
  decoration: const InputDecoration(
         


        
9条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 01:01

    With a credit goes to X-Wei, you can create the widget as a separate password.dart:

    import 'package:flutter/material.dart';
    
    class PasswordField extends StatefulWidget {
      const PasswordField({
        this.fieldKey,
        this.hintText,
        this.labelText,
        this.helperText,
        this.onSaved,
        this.validator,
        this.onFieldSubmitted,
      });
    
      final Key fieldKey;
      final String hintText;
      final String labelText;
      final String helperText;
      final FormFieldSetter onSaved;
      final FormFieldValidator validator;
      final ValueChanged onFieldSubmitted;
    
      @override
      _PasswordFieldState createState() => new _PasswordFieldState();
    }
    
    class _PasswordFieldState extends State {
      bool _obscureText = true;
    
      @override
      Widget build(BuildContext context) {
        return new TextFormField(
          key: widget.fieldKey,
          obscureText: _obscureText,
          maxLength: 8,
          onSaved: widget.onSaved,
          validator: widget.validator,
          onFieldSubmitted: widget.onFieldSubmitted,
          decoration: new InputDecoration(
            border: const UnderlineInputBorder(),
            filled: true,
            hintText: widget.hintText,
            labelText: widget.labelText,
            helperText: widget.helperText,
            suffixIcon: new GestureDetector(
              onTap: () {
                setState(() {
                  _obscureText = !_obscureText;
                });
              },
              child:
              new Icon(_obscureText ? Icons.visibility : Icons.visibility_off),
            ),
          ),
        );
      }
    }
    

    Call it as:

      import 'package:my_app/password.dart';
    
      String _password;
      final _passwordFieldKey = GlobalKey>();
    
      PasswordField(
        fieldKey: _passwordFieldKey,
        helperText: 'No more than 8 characters.',
        labelText: 'Password *',
        onFieldSubmitted: (String value) {
          setState(() {
            this._password = value;
          });
        },
      ),
    

提交回复
热议问题