本文介绍了如何在 TextFormField 中显示/隐藏密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我的密码 TextFormField 是这样的:

Currently I have my password TextFormField like this:

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,
);

我想要一个类似交互的按钮,可以使密码可见和不可见.我可以在 TextFormField 里面做吗?或者我将不得不制作一个 Stack 小部件来获得我需要的 UI.关于 obscureText 真/假的条件如何制定?

I want a button like interaction which will make password visible and invisible. Can I do it inside TextFormField? Or I will have to make a Stack widget to get my required UI. And how will the condition be made regarding obscureText true/false?

推荐答案

首先让你的小部件 StatefulWidget 如果它是一个 StatelessWidget.

First make you widget StatefulWidget if it is a StatelessWidget.

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

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

示例:

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"))
          ],
        ),
      ),
    );
  }
}

希望这有帮助!

这篇关于如何在 TextFormField 中显示/隐藏密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 07:42