0

I have various text field widgets for passwords in my project and all of them have the obscure text property, how do I add an icon that allows to show and hide the text in the text field anytime it's clicked?

Iniisking
  • 45
  • 6

3 Answers3

1
import 'package:flutter/material.dart';

class MainClass extends StatefulWidget {
  const MainClass({Key key}) : super(key: key);

  @override
  _MainClassState createState() => _MainClassState();
}

class _MainClassState extends State<MainClass> {
  bool _isObscure = false;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Sample"),
      ),
      body: new Container(
        child: new Column(
          children: <Widget>[
            TextField(
              obscureText: _isObscure,
              decoration: InputDecoration(
                labelText: 'Password',
                // this button is used to toggle the password visibility
                suffixIcon: IconButton(
                  icon: Icon(_isObscure ? Icons.visibility : Icons.visibility_off),
                  onPressed: () {
                    setState(() {
                      _isObscure = !_isObscure;
                    });
                  }
                )
              ),
            ),
          ],
        ),
      ),
    );
  }
}
0

You can add a decoration to the TextField:

TextField(
//    ...,
      decoration: InputDecoration(
        prefixIcon:Icon(Icons.password),
      ),
    ),
Alaindeseine
  • 3,260
  • 1
  • 11
  • 21
0

Add suffix inside inputDecoration and change the state on clicking the suffix widget.

decoration:InputDecoration(
    hintText: 'First name',
    icon: Icon(Icons.add),
    suffix: GestureDetector(child: Icon(Icons.remove), onTap: () {},),
),
Phanindra
  • 1,110
  • 2
  • 11
  • 24