基于文本字段上的用户输入的 Flutter 禁用和启用按钮
Flutter Disable and Enable Button based on the user input on textfield
如何在用户尚未向文本字段添加任何内容时禁用按钮,然后在用户键入内容后启用它?
可能吗?如果没有,还有其他方法吗?
谢谢
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,
),
],
);
使用文本编辑控制器https://flutter.dev/docs/cookbook/forms/text-field-changes
final controller = TextEditingController();
onPressed: controller.text.length==0 ? null : _sendNewMessage,
请检查.length是否正确记不住哈哈
要实现这一点,您必须从文本字段中获取输入的长度,正确的方法是使用 TextEditingController,但为了这个简单的目的,一个变通方法应该可以完成这项工作。
代码:
在 return AlertDialog
之前初始化一个新的 bool isInputEmpty
onChanged: (value) {
setState(() {
_newMessage = value;
if(_newMessage.length > 0){ //add these lines
isInputEmpty = false;
} else {
isInputEmpty = true;
}
});
},
要禁用按钮,您可以将他包裹在 IgnorePointer
中
IgnorePointer(
ignoring: isInputEmpty,
child: IconButton(...),
),
您甚至可以更改按钮颜色:
IconButton(
color: isInputEmpty ? Colors.grey : Colors.tealAccent,
),
如何在用户尚未向文本字段添加任何内容时禁用按钮,然后在用户键入内容后启用它?
可能吗?如果没有,还有其他方法吗?
谢谢
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,
),
],
);
使用文本编辑控制器https://flutter.dev/docs/cookbook/forms/text-field-changes
final controller = TextEditingController();
onPressed: controller.text.length==0 ? null : _sendNewMessage,
请检查.length是否正确记不住哈哈
要实现这一点,您必须从文本字段中获取输入的长度,正确的方法是使用 TextEditingController,但为了这个简单的目的,一个变通方法应该可以完成这项工作。
代码:
在 return AlertDialog
onChanged: (value) {
setState(() {
_newMessage = value;
if(_newMessage.length > 0){ //add these lines
isInputEmpty = false;
} else {
isInputEmpty = true;
}
});
},
要禁用按钮,您可以将他包裹在 IgnorePointer
中IgnorePointer(
ignoring: isInputEmpty,
child: IconButton(...),
),
您甚至可以更改按钮颜色:
IconButton(
color: isInputEmpty ? Colors.grey : Colors.tealAccent,
),