Password show or hide icon

  • Steps
    
    
                  import 'package:flutter/material.dart';
    import 'package:get/get.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class PasswordController extends GetxController {
      var isObscure = true.obs;
    
      void togglePasswordVisibility() {
        isObscure.value = !isObscure.value;
      }
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return GetMaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Password Show/Hide'),
            ),
            body: Center(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: PasswordField(),
              ),
            ),
          ),
        );
      }
    }
    
    class PasswordField extends StatelessWidget {
      final PasswordController passwordController = Get.put(PasswordController());
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(
              () => TextField(
                obscureText: passwordController.isObscure.value,
                decoration: InputDecoration(
                  labelText: 'Password',
                  suffixIcon: IconButton(
                    icon: Icon(
                      passwordController.isObscure.value ? Icons.visibility : Icons.visibility_off,
                    ),
                    onPressed: () {
                      passwordController.togglePasswordVisibility();
                    },
                  ),
                ),
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // Perform actions with the entered password
              },
              child: Text('Submit'),
            ),
          ],
        );
      }
    }
    
    
    

    In this example, the PasswordController manages the state of the password visibility using GetX. The PasswordField widget contains a TextField where the obscureText property is controlled by the isObscure value. Additionally, an IconButton is used as a suffix icon in the TextField to toggle the visibility of the password text.

    The togglePasswordVisibility function in the controller switches the value of isObscure between true and false when the user taps the visibility icon.