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

前端之家收集整理的这篇文章主要介绍了android – 如何在TextFormField中显示/隐藏密码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我有我的密码TextFormField像这样:

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: true,),

我想要一个像交互一样的按钮,这会使密码可见和不可见.我可以在TextFormField中执行此操作吗?或者我必须制作一个Stack小部件来获取我所需的UI.那么关于obscureText的条件是如何实现的呢?

解决方法

如果它是StatelessWidget,首先使您成为StatefulWidget.

然后有一个变量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,obscureText: _obscureText,new FlatButton(
                onPressed: _toggle,child: new Text(_obscureText ? "Show" : "Hide"))
          ],);
  }
}

希望这可以帮助!

猜你在找的Flutter相关文章