I want text button to show grey color when text field is empty and green when some text is entered into the text field. How would i do that??
TextField (),
TextButton(
child: Text("Press Here"),
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)){
return Colors.green;}
return Colors.grey;
}
),
),
),
CodePudding user response:
check you input text is empty?
TextEditingController textEditingController = TextEditingController();
bool isTextEmpty;
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: textEditingController,
onChanged: (value) {
setState(() {
if (value.length > 0) {
isTextEmpty = true;
} else {
isTextEmpty = false;
}
});
},
),
TextButton(
child: Text("Press Here"),
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (isTextEmpty) {
return Colors.green;
}
return Colors.grey;
}),
),
),
],
);
}
CodePudding user response:
You can keep TextButton
's background color to a variable and then change the variable's value when TextField's
value changes occurred in the onChange
callback.
Checkout this sample code:
Color primaryColor = Colors.grey;
Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
onChanged: (val) {
setState(() {
primaryColor = val.isNotEmpty ? Colors.green : Colors.grey;
});
},
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey.shade50,
),
),
const SizedBox(height: 16),
SizedBox(
width: MediaQuery.of(context).size.width,
child: TextButton(
onPressed: () {},
style: TextButton.styleFrom(backgroundColor: primaryColor),
child: Text("Submit"),
),
),
],
)