androidflutterflutter-android

Flutter TextFormField( decoration: ..., suffix: IconButton( onPressed: , )); icon button onPress error


I want to give my input type as password so I want it as censored. I want to use "obscureText: true," so it works but when I want to declare it a function and add a button that will show the password when you click and hide when you click it again. I am trying to add suffix property and IconButton(); but it is not working.

bool hide() {
  return true;
}

@override
Widget build(BuildContext context){
  return Form(
    key: loginClass,
    ...
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 8),
          child: TextFormField(
            controller: password,
            obscureText: hide(),
            decoration: const InputDecoration(
              labelText: "Password",
              hintText: "Enter your password",
              border: OutlineInputBorder(),
              icon: Icon(Icons.lock),

              // Suffix line.

              suffix: IconButton(
                icon: Icon(Icons.visibility_rounded),
                onPressed: !hide, // Error line.
              ),

            ),
            validator: (String? value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your password';
              }
              return null;
            },
          ),
        ),
       ...
}

Error:

Performing hot restart...
Syncing files to device Android SDK built for x86...

lib/login.dart:107:31: Error: Not a constant expression.
                  onPressed: !hide,
                              ^^^^

lib/login.dart:107:31: Error: A value of type 'bool Function()' can't be assigned to a variable of type 'bool'.
                  onPressed: !hide,
                              ^

lib/login.dart:107:30: Error: The argument type 'bool' can't be assigned to the parameter type 'void Function()?'.
                  onPressed: !hide,
                             ^

Restarted application in 218ms.

I want to add a icon button. Once you click it, the password will be shown but if you click again will be censored.


Solution

  • You must declare a boolean variable and change its value depending on the visibility button. Also, if you do not use BLOC or GETX, you must use a stateful widget to obtain the screens' updates. Also, Do not use const if you assign an onPressed function with a function or setState. I have done an example code for you... you can try it directly on the browser through this link: https://zapp.run/edit/flutter-zn206ban306?entry=lib/main.dart&file=lib/main.dart