如何在TextFormField中显示/隐藏密码?

Far*_*rwa 15 android dart flutter

目前我有我的密码TextFormField像这样:

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: true,
);
Run Code Online (Sandbox Code Playgroud)

我想要一个像交互一样的按钮,这会使密码可见和不可见.我可以在里面做TextFormField吗?或者我必须创建一个TextFormField小部件来获取我所需的UI.那么关于Stack真/假的条件如何?

Par*_*lke 38

我按照@Hemanth Raj创建了解决方案,但是更加强大.

首先声明一个bool变量passwordVisible.

启动passwordVisible到false中initState()

@override
  void initState() {
    passwordVisible = false;
  }
Run Code Online (Sandbox Code Playgroud)

以下是TextFormField小部件:

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;
               });
             },
            ),
          ),
        );
Run Code Online (Sandbox Code Playgroud)

希望这能帮助别人!

  • 在默认的正常情况下,页面加载密码是模糊的,因此将把passwordVisible初始化为true,即``passwordVisible= true```,并使其在这种情况下有意义,将变量``passwordVisible```替换为`` `密码模糊= true``` (6认同)
  • 添加到纳尔逊指出的内容中,对此的一个简单解决方法是执行 `obscureText: !passwordVisible` (5认同)

Hem*_*Raj 35

StatefulWidget如果它是一个,首先使你成为小部件StatelessWidget.

然后有一个变量bool _obscureText并将其传递给您TextFormField.根据需要切换它setState.

例:

class _FormFieldSampleState extends State<FormFieldSample> {

  // 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: <Widget>[
            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"))
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 不需要Stack.`InputDecoration`有一个[`suffixIcon`](https://docs.flutter.io/flutter/material/InputDecoration/suffixIcon.html)属性,这可能正是你正在寻找的. (6认同)

Bug*_*lla 24

此解决方案可防止 suffixIcon 中的点击将焦点赋予 TextField,但如果 TextField 已获得焦点并且用户想要显示/隐藏密码,则焦点不会丢失。

结果

import 'package:flutter/material.dart';

class PasswordField extends StatefulWidget {
  const PasswordField({Key? key}) : super(key: key);

  @override
  _PasswordFieldState createState() => _PasswordFieldState();
}

class _PasswordFieldState extends State<PasswordField> {
  final textFieldFocusNode = FocusNode();
  bool _obscured = false;

  void _toggleObscured() {
    setState(() {
      _obscured = !_obscured;
      if (textFieldFocusNode.hasPrimaryFocus) return; // If focus is on text field, dont unfocus
      textFieldFocusNode.canRequestFocus = false;     // Prevents focus if tap on eye
    });
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      keyboardType: TextInputType.visiblePassword,
      obscureText: _obscured,
      focusNode: textFieldFocusNode,
      decoration: InputDecoration(
        floatingLabelBehavior: FloatingLabelBehavior.never, //Hides label on focus or if filled
        labelText: "Password",
        filled: true, // Needed for adding a fill color
        fillColor: Colors.grey.shade800, 
        isDense: true,  // Reduces height a bit
        border: OutlineInputBorder(
          borderSide: BorderSide.none,              // No border
          borderRadius: BorderRadius.circular(12),  // Apply corner radius
        ),
        prefixIcon: Icon(Icons.lock_rounded, size: 24),
        suffixIcon: Padding(
          padding: const EdgeInsets.fromLTRB(0, 0, 4, 0),
          child: GestureDetector(
            onTap: _toggleObscured,
            child: Icon(
              _obscured
                  ? Icons.visibility_rounded
                  : Icons.visibility_off_rounded,
              size: 24,
            ),
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Has*_*sef 15

归功于X-Wei,您可以将小部件创建为单独的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<String> onSaved;
  final FormFieldValidator<String> validator;
  final ValueChanged<String> onFieldSubmitted;

  @override
  _PasswordFieldState createState() => new _PasswordFieldState();
}

class _PasswordFieldState extends State<PasswordField> {
  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),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

称之为:

  import 'package:my_app/password.dart';

  String _password;
  final _passwordFieldKey = GlobalKey<FormFieldState<String>>();

  PasswordField(
    fieldKey: _passwordFieldKey,
    helperText: 'No more than 8 characters.',
    labelText: 'Password *',
    onFieldSubmitted: (String value) {
      setState(() {
        this._password = value;
      });
    },
  ),
Run Code Online (Sandbox Code Playgroud)


小智 11

我通过按住并释放 longTap 做到了这一点:

    bool _passwordVisible;

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

// ...
TextFormField(
  obscureText: !_passwordVisible,
  decoration: InputDecoration(
    hasFloatingPlaceholder: true,
    filled: true,
    fillColor: Colors.white.withOpacity(0.5),
    labelText: "Password",
    suffixIcon: GestureDetector(
      onLongPress: () {
        setState(() {
          _passwordVisible = true;
        });
      },
      onLongPressUp: () {
        setState(() {
          _passwordVisible = false;
        });
      },
      child: Icon(
          _passwordVisible ? Icons.visibility : Icons.visibility_off),
    ),
  ),
  validator: (String value) {
    if (value.isEmpty) {
      return "*Password needed";
    }
  },
  onSaved: (String value) {
    _setPassword(value);
  },
);
Run Code Online (Sandbox Code Playgroud)


mah*_*mnj 11

好吧,我个人喜欢一直隐藏密码,并在您想看到它们时看到,所以这是我用来隐藏/取消隐藏密码的方法,如果您希望在触摸时看到密码 与隐藏图标,并在您删除联系人后立即隐藏,那么这是给您的

//make it invisible globally
  bool invisible = true;

//wrap your toggle icon in Gesture Detector
  GestureDetector(
   onTapDown: inContact,//call this method when incontact
   onTapUp: outContact,//call this method when contact with screen is removed
   child: Icon(
   Icons.remove_red_eye,
   color: colorButton,
   ),
  ),

  void inContact(TapDownDetails details) {
    setState(() {
      invisible = false;
    });
  }

  void outContact(TapUpDetails details) {
    setState(() {
      invisible=true;
    });
  }
Run Code Online (Sandbox Code Playgroud)

我的包https://pub.dev/packages/passwordfield正在使用这种方法

上面代码的输出

在此处输入图片说明


Nik*_*the 10


\n

\xe2\x97\x8b 只需遵循简单的 3 个步骤即可完成密码显示/隐藏。

\n
\n

在此输入图像描述

\n

第1步:创建变量

\n
       bool _isHidden = true;\n
Run Code Online (Sandbox Code Playgroud)\n

第 2 步:神奇的一步,使图标可点击并查看/隐藏密码。

\n

现在我将用 InkWell 包裹图标,使其可点击。因此,当我们单击它时,它将在“obviousText”参数之间切换“真”和“假”。

\n
 @override\n   Widget build(BuildContext context) {\n     return Scaffold(\n        backgroundColor: Theme.of(context).secondaryHeaderColor,\n          body: Center(\n            child: Container(\n            height: 55,\n            alignment: Alignment.center,\n            padding: EdgeInsets.fromLTRB(10, 10, 10, 0),\n            child: TextField(\n              obscureText: _isHidden,\n              decoration: InputDecoration(\n                border: OutlineInputBorder(),\n                labelText: \'Password\',\n                suffix: InkWell(\n                  onTap: _togglePasswordView,  /// This is Magical Function\n                  child: Icon(\n                    _isHidden ?         /// CHeck Show & Hide.\n                     Icons.visibility :\n                     Icons.visibility_off,\n                  ),\n                ),\n                /*icon: Icon(\n                  Icons.password_sharp,\n                  color: Colors.black,\n                ),*/\n              ),\n            ),\n          ),\n        ),\n     );\n  }\n
Run Code Online (Sandbox Code Playgroud)\n

第三步:创建这个神奇的函数。

\n
      void _togglePasswordView() {\n    setState(() {\n        _isHidden = !_isHidden;\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\n