Home > Net >  Toggle password visibility using Gesture Detector
Toggle password visibility using Gesture Detector

Time:08-10

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

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

CodePudding user response:

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(....)

  • Related