首页 > 解决方案 > 如何在颤动中显示/隐藏密码?

问题描述

我已经为我的应用程序创建了一个登录屏幕,但是在密码字段中,我想要一个功能,例如当我输入密码时,它的格式是 * 格式,并且当用户单击它时,右侧会显示一个图标,密码将可见,我创建了一个代码但是当我单击密码字段时,该图标变得不可见并且当密码字段失去焦点时,该图标再次出现,那么即使密码字段处于焦点,如何始终显示该图标?我提供了一个快照以轻松理解问题。

在此处输入图像描述

在此处输入图像描述

这是我的登录屏幕代码....

import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
import 'package:secret_keeper/screens/home_screen/Home.dart';
import 'package:secret_keeper/screens/home_screen/passwords/PasswordsNavigation.dart';
import 'package:secret_keeper/screens/signup_page/SignupPage.dart';

class LoginPage extends StatefulWidget{
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  String _emailID, _password = "",_email = "abc@gmail.com", _pass = "Try.t.r.y@1";
  bool _obscureText = true;
  final _formKey = GlobalKey<FormState>();
  
  void _toggle(){
    setState(() {
      _obscureText = !_obscureText;
    });
  }

  void validateLogin(){
    if(_formKey.currentState.validate()){
      _formKey.currentState.save();
      if(_emailID == _email && _password == _pass){
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Home()));
      }
    }
  }

  Widget emailInput(){
    return TextFormField(
      keyboardType: TextInputType.emailAddress,
      decoration: InputDecoration(
        labelText: "Email ID",
        labelStyle: TextStyle(fontSize: 14,color: Colors.grey.shade400),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(
            color: Colors.grey.shade300,
          ),
        ),
        focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10),
            borderSide: BorderSide(
              color: Colors.red,
            )
        ),
      ),
      validator: (email) {
        if (email.isEmpty)
          return 'Please Enter email ID';
        else if (!EmailValidator.validate(email))
          return 'Enter valid email address';
        else
          return null;
      },
      onSaved: (email)=> _emailID = email,
      textInputAction: TextInputAction.next,
    );
  }

  Widget passInput(){
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: InputDecoration(
        labelText: "Password",
        labelStyle: TextStyle(fontSize: 14,color: Colors.grey.shade400),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(
            color: Colors.grey.shade300,
          ),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(
            color: Colors.red,
          )
        ),
        suffixIcon: IconButton(
          icon: Icon(
            _obscureText ? Icons.visibility : Icons.visibility_off,
          ),
          onPressed: _toggle,
        ),
      ),
      validator: (password){
        Pattern pattern =
            r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';
        RegExp regex = new RegExp(pattern);
        if (password.isEmpty){
          return 'Please Enter Password';
        }else if (!regex.hasMatch(password))
          return 'Enter valid password';
        else
          return null;
      },
      onSaved: (password)=> _password = password,
      textInputAction: TextInputAction.done,
      obscureText: _obscureText,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.only(left: 16,right: 16),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(height: 50,),
                    Text("Welcome,",style: TextStyle(fontSize: 26,fontWeight: FontWeight.bold),),
                    SizedBox(height: 6,),
                    Text("Sign in to continue!",style: TextStyle(fontSize: 20,color: Colors.grey.shade400),),
                  ],
                ),
                Column(
                  children: <Widget>[
                    emailInput(),
                    SizedBox(height: 16,),
                    passInput(),
                    SizedBox(height: 12,),
                    Align(
                      alignment: Alignment.topRight,
                      child: Text("Forgot Password ?",style: TextStyle(fontSize: 14,fontWeight: FontWeight.w600),),
                    ),
                    SizedBox(height: 30,),
                    Container(
                      height: 50,
                      width: double.infinity,
                      child: FlatButton(
                        onPressed: validateLogin,
                        padding: EdgeInsets.all(0),
                        child: Ink(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6),
                            gradient: LinearGradient(
                              begin: Alignment.centerLeft,
                              end: Alignment.centerRight,
                              colors: [
                                Color(0xffff5f6d),
                                Color(0xffff5f6d),
                                Color(0xffffc371),
                              ],
                            ),
                          ),
                          child: Container(
                            alignment: Alignment.center,
                            constraints: BoxConstraints(maxWidth: double.infinity,minHeight: 50),
                            child: Text("Login",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),textAlign: TextAlign.center,),
                          ),
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(6),
                        ),
                      ),
                    ),
                    SizedBox(height: 16,),
                    Container(
                      height: 50,
                      width: double.infinity,
                      child: FlatButton(
                        onPressed: (){},
                        color: Colors.indigo.shade50,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset("assets/images/facebook.png",height: 18,width: 18,),
                            SizedBox(width: 10,),
                            Text("Connect with Facebook",style: TextStyle(color: Colors.indigo,fontWeight: FontWeight.bold),),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 16,),
                    Container(
                      height: 50,
                      width: double.infinity,
                      child: FlatButton(
                        onPressed: (){},
                        color: Colors.indigo.shade50,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset("assets/images/facebook.png",height: 18,width: 18,),
                            SizedBox(width: 10,),
                            Text("Connect with Facebook",style: TextStyle(color: Colors.indigo,fontWeight: FontWeight.bold),),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text("Don't have an account?",style: TextStyle(fontWeight: FontWeight.bold),),
                      SizedBox(width: 5,),
                      GestureDetector(
                        onTap: (){
                          Navigator.push(context, MaterialPageRoute(builder: (context){
                            return SignupPage();
                          }));
                        },
                        child: Text("Sign up",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.red),),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

标签: flutter

解决方案


这里有两种情况

  1. 如果你想让你的后缀图标颜色像总是灰色一样,你可以给图标的颜色属性,比如:

密码显示隐藏按钮

var passShowButton = GestureDetector(
      onLongPressEnd: outContact,
      onTapDown: inContact, //call this method when incontact
      onTapUp:
          outContact, //call this method when contact with screen is removed
      child: Icon(
        getXHelper.isEmailPasswordUpdate.isTrue
            ? AppIcons.hidePassword
            : AppIcons.hidePassword,
        size: 18,
        color:Colors.grey
      ),
    );

文本域

TextField(
    obscureText: getXHelper.isPassInvisible  ,
    autocorrect: false,
    textAlignVertical: TextAlignVertical.bottom,
    decoration: InputDecoration(
      enabled: true,
      errorBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      border: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      fillColor: Colors.white,
      filled: true,
      isDense: true,
      prefixIconConstraints: BoxConstraints(maxHeight: 18, minHeight: 18),
      hintText: "Password",
      prefixIcon: Padding(
        padding: const EdgeInsets.only(top: 0, right: 12, bottom: 0),
        child: Icon(Icons.lock, size: 18, color: Colors.grey),
      ),
      suffixIcon: passShowButton,
    ),
    cursorColor: Colors.black,
    style: TextStyle(
        color: Colors.black, fontFamily: AppFontFamily.fontFamily),
  )
  1. 如果您希望应用程序主颜色的后缀图标颜色,将在文本字段焦点时更改颜色,例如:

密码显示隐藏按钮

var passShowButton = GestureDetector(
          onLongPressEnd: outContact,
          onTapDown: inContact, //call this method when incontact
          onTapUp:
              outContact, //call this method when contact with screen is removed
          child: Icon(
            getXHelper.isEmailPasswordUpdate.isTrue
                ? AppIcons.hidePassword
                : AppIcons.hidePassword,
            size: 18,
          ),
        );

TextField(
    obscureText: getXHelper.isPassInvisible  ,
    autocorrect: false,
    textAlignVertical: TextAlignVertical.bottom,
    decoration: InputDecoration(
      enabled: true,
      errorBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      border: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary)),
      fillColor: Colors.white,
      filled: true,
      isDense: true,
      prefixIconConstraints: BoxConstraints(maxHeight: 18, minHeight: 18),
      hintText: "Password",
      prefixIcon: Padding(
        padding: const EdgeInsets.only(top: 0, right: 12, bottom: 0),
        child: Icon(Icons.lock, size: 18),
      ),
      suffixIcon: passShowButton,
    ),
    cursorColor: Colors.black,
    style: TextStyle(
        color: Colors.black, fontFamily: AppFontFamily.fontFamily),
  )

推荐阅读