Reputation: 127
How can I disable a button when the user hasn't added any content to the textfield yet and then enable it once the user type something?
Is it possible? And if no is there another way to do it?
Thanks
return AlertDialog(
contentPadding: EdgeInsets.only(top: 5.0),
content: Padding(
padding: EdgeInsets.only(left: 15.0, right: 15.0, bottom: 20.0),
child: TextField(
keyboardType: TextInputType.multiline,
decoration: InputDecoration(labelText: 'Send a new message...'),
onChanged: (value) {
setState(() {
_newMessage = value;
});
},
),
),
actions: [
IconButton(
color: Colors.tealAccent,
icon: Icon(
Icons.navigate_next_rounded,
size: 40.0,
),
onPressed: _newMessage.trim().isEmpty ? null : _sendNewMessage,
),
],
);
Upvotes: 1
Views: 2110
Reputation: 3162
To achive this you have to get the lenght of the input from the textfield, the correct way is to use a TextEditingController but for this simple purpose a workarount should do the job.
Code:
Initialize a new bool isInputEmpty before the return AlertDialog
onChanged: (value) {
setState(() {
_newMessage = value;
if(_newMessage.length > 0){ //add these lines
isInputEmpty = false;
} else {
isInputEmpty = true;
}
});
},
and to disable to button you can wrap him inside a IgnorePointer
IgnorePointer(
ignoring: isInputEmpty,
child: IconButton(...),
),
You can even change the button color:
IconButton(
color: isInputEmpty ? Colors.grey : Colors.tealAccent,
),
Upvotes: 2
Reputation: 636
Use a Text Editing Controller https://flutter.dev/docs/cookbook/forms/text-field-changes
final controller = TextEditingController();
onPressed: controller.text.length==0 ? null : _sendNewMessage,
pls check if the .length is correct can't remember haha
Upvotes: 2