我做了一个删除按钮,弹出一个对话框,让你记录删除的原因。我只希望在用户输入原因时启用提交按钮。下面是我为该小部件所做的:
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'),
),
],
),
),
);
}
}
当我运行它并输入注解时,按钮保持禁用状态。我在构建时打印状态的值,当我输入时,它确实更改为启用。当我退出图标并返回时,它然后显示启用,即使注解是空的。但当我输入注解时,它永远不会更改。
有什么想法吗
3条答案
按热度按时间5t7ly7z51#
理想情况下你需要两样东西
1.对话框关闭后重置
enabled
和note
的值。因此,等待对话框关闭并根据您的需要重置值。下面是修改后的代码:
注意:您并不总是需要用setState Package 变量来进行更新,只需调用setState就会自动用更新后的变量更新widget树。
ar7v8xwq2#
我不知道我是否理解正确,但禁用“确定”按钮,直到用户输入原因:
验证码:
看看我能不能帮你解决这个问题。
eit6fx6z3#
这是TextEditingController的更正: