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

新手上路,请多包涵

目前我有我的密码 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,
);

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

原文由 Farwa 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 950
2 个回答

首先让你的小部件 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"))
          ],
        ),
      ),
    );
  }
}

希望这可以帮助!

原文由 Hemanth Raj 发布,翻译遵循 CC BY-SA 3.0 许可协议

//Password
const TextField(
  obscureText: true, //for hide Password
  decoration: InputDecoration(
      prefixIcon: Icon(Icons.lock_outline),
      hintText: 'Password'),
),

原文由 Sarthak Raval 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题