How to show/hide password in TextFormField?

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

Currently I have my password TextFormField like this:

TextFormField(
  decoration: const InputDecoration(
         


        
9条回答
  •  礼貌的吻别
    2021-02-01 01:12

    I have created a solution as per @Hemanth Raj but in a more robust way.

    First declare a bool variable _passwordVisible.

    Initiate _passwordVisible to false in initState()

    @override
      void initState() {
        _passwordVisible = false;
      }
    

    Following is the TextFormField widget :

    TextFormField(
       keyboardType: TextInputType.text,
       controller: _userPasswordController,
       obscureText: !_passwordVisible,//This will obscure text dynamically
       decoration: InputDecoration(
           labelText: 'Password',
           hintText: 'Enter your password',
           // Here is key idea
           suffixIcon: IconButton(
                icon: Icon(
                  // Based on passwordVisible state choose the icon
                   _passwordVisible
                   ? Icons.visibility
                   : Icons.visibility_off,
                   color: Theme.of(context).primaryColorDark,
                   ),
                onPressed: () {
                   // Update the state i.e. toogle the state of passwordVisible variable
                   setState(() {
                       _passwordVisible = !_passwordVisible;
                   });
                 },
                ),
              ),
            );
    

提交回复
热议问题