I made a delete button that pops up a dialog and makes you record the reason for the delete. I only want the submit button enabled if the user enters a reason. Here is what I have for that widget:
class _DeleteCrewMemberWidgetState extends State<DeleteCrewMemberWidget> {
var note = '';
@override
Widget build(BuildContext context) {
bool enabled = note.length >= 10;
// delete this member
delete() {
Navigator.pop(context, 'OK');
}
print(enabled);
return IconButton(
icon: Icon(Icons.remove_circle),
onPressed: () => showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text('Delete ${widget.position.name}'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Please enter a reason for not needing this crew member.'),
TextField(
maxLines: 4,
onChanged: (value) => setState(() {
note = value;
print(note);
}),
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter your reason here',
),
),
],
),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
TextButton(
onPressed: enabled ? () => delete() : null,
child: const Text('OK'),
),
],
),
),
);
}
}
When I run it and type in a note, the button stays disabled. I print the value of the state on build, and it does change to enabled as I type. When I get out of the icon and back in, it then shows enabled, even though the note is empty. But it never changes while I’m typing the note.
Any ideas?
3
Answers
I don’t know if I understand correctly, but disable the "OK" button until the user enters a reason:
your code:
See if I could help you with the problem.
Ideally you need two things here
enabled
andnote
once the dialog is closed. So wait for the Dialog to close and reset the value as per your need.Here’s the modified code :
Note: You do not always need to wrap your variables with setState to update. Just calling the setState will automatically update the widget tree with updated variables.
This is a correction with TextEditingController: