I have a TextFormField and i want its suffix icon auto hidden when the textfield is empty. Here is my code
child: TextFormField(
decoration: InputDecoration(
contentPadding:
const EdgeInsets.only(top: 16, bottom: 15),
border: InputBorder.none,
fillColor: Colors.white,
prefixIcon: const Padding(
padding: EdgeInsets.only(top: 16.0, bottom: 15),
child: Text("Code: "),
),
prefixIconConstraints: const BoxConstraints(minWidth: 60, minHeight: 19),
hintText: "Input code here ",
suffixIcon: IconButton(
onPressed: () {
},
icon: Icon(Icons.delete),
),
),
keyboardType: TextInputType.number,
),
This is how it should look like
Can anyone help me pls.
CodePudding user response:
You can use TextEditingController
with a listner
late final TextEditingController controller = TextEditingController()
..addListener(() {
setState(() {});
});
TextFormField(
controller: controller,
decoration: InputDecoration(
suffixIcon: controller.text.isEmpty
? null
: IconButton(
onPressed: () {},
icon: Icon(Icons.delete),
),
CodePudding user response:
late final TextEditingController controller = TextEditingController()
..addListener(() {
if(controller.text.isEmpty){
setState(() {});
}
});
child: TextFormField(
decoration: InputDecoration(
contentPadding:
const EdgeInsets.only(top: 16, bottom: 15),
border: InputBorder.none,
fillColor: Colors.white,
prefixIcon: const Padding(
padding: EdgeInsets.only(top: 16.0, bottom: 15),
child: Text("Code: "),
),
prefixIconConstraints: const BoxConstraints(minWidth: 60, minHeight: 19),
hintText: "Input code here ",
suffixIcon: controller.text.isEmpty
? null
: IconButton(
onPressed: () {},
icon: Icon(Icons.delete),
),
),
keyboardType: TextInputType.number,
),
CodePudding user response:
You can also do it using onChanged
and setState
.
bool show= false;
child:TextFormField(
onChanged: (value){
if(value.isNotEmpty){
setState(() {
show=true;
});
}
else{
setState(() {
show=false;
});
}
} ,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.only(top: 16, bottom: 15),
border: InputBorder.none,
fillColor: Colors.white,
prefixIcon: const Padding(
padding: EdgeInsets.only(top: 16.0, bottom: 15),
child: Text("Code: "),
),
prefixIconConstraints: const BoxConstraints(minWidth: 60, minHeight: 19),
hintText: "Input code here ",
suffixIcon:show? IconButton(
onPressed: () {
},
icon: Icon(Icons.delete),
):null,
),
keyboardType: TextInputType.number,
),