Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Toggle password visibility using Gesture Detector

I’m new to flutter and following a tutorial where using an icon, the visibility of a password changes from hidden to visible.
I saw some cases where IconButton is used but even though I tried that method I’m still getting red lines everywhere. I wish to know where exactly the problem is unless it’s a version related issue.

the variables are defined as such:

  late String _password, _email;
  bool _isObscure = true;

The Form Field

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Widget _showPasswordInput() {
    return TextFormField(
      onSaved: (val) => _password = val!,
      obscureText: _isObscure,
      decoration: const InputDecoration(
        // border: OutlineInputBorder(),
        suffixIcon: GestureDetector(
          onTap: () {
            setState(() {
              _isObscure = !_isObscure;
            });
          },
          child: Icon(
            _isObscure ? Icons.visibility : Icons.visibility_off,
          ),
        ),
        labelText: 'Password',
        hintText: 'Enter valid password, min: 6 chars',
        icon: Icon(Icons.lock),
      ),
      validator: (value) {
        if (value!.isEmpty) {
          return 'Please enter some text';
        }
        return null;
  
      },
    );
  }

How it’s used in the build

Widget build(BuildContext context) {
    return Scaffold(

      body: Container(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Center(
            child: SingleChildScrollView(
                child: Form(
                    key: _formKey,
                    child: Column(children: <Widget>[
                      _showRegisterButton(),
                    ]))),
          )),
    );
  }

>Solution :

Inside InputDecoration, data is changing on runtime, therefore it cannot be const

decoration: InputDecoration(
  // border: OutlineInputBorder(),
  suffixIcon: GestureDetector(
    onTap: () {
      setState(() {
        _isObscure = !_isObscure;
      });
    },
    child: Icon(
      _isObscure ? Icons.visibility : Icons.visibility_off,
    ),
  ),

and create a method like myTextFiled(BuildContext context) => TextFormField(....)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading