How to show/hide password in TextFormField?

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

Currently I have my password TextFormField like this:

TextFormField(
  decoration: const InputDecoration(
         


        
9条回答
  •  你的背包
    2021-02-01 01:12

    First make you widget StatefulWidget if it is a StatelessWidget.

    Then have a variable bool _obscureText and pass it to your TextFormField. The toggle it with setState as required.

    Example:

    class _FormFieldSampleState extends State {
    
      // Initially password is obscure
      bool _obscureText = true;
    
      String _password;
    
      // Toggles the password show status
      void _toggle() {
        setState(() {
          _obscureText = !_obscureText;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("Sample"),
          ),
          body: new Container(
            child: new Column(
              children: [
                new TextFormField(
                  decoration: const InputDecoration(
                      labelText: 'Password',
                      icon: const Padding(
                          padding: const EdgeInsets.only(top: 15.0),
                          child: const Icon(Icons.lock))),
                  validator: (val) => val.length < 6 ? 'Password too short.' : null,
                  onSaved: (val) => _password = val,
                  obscureText: _obscureText,
                ),
                new FlatButton(
                    onPressed: _toggle,
                    child: new Text(_obscureText ? "Show" : "Hide"))
              ],
            ),
          ),
        );
      }
    }
    

    Hope this helps!

提交回复
热议问题