问题描述
当前,我的密码为 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?
推荐答案
首先,如果它是 StatelessWidget
,则将其置为 StatefulWidget
.
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中显示/隐藏密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!