Flutter 基于文本字段上的用户输入禁用和启用按钮

问题描述

如何在用户尚未向文本字段添加任何内容时禁用按钮,然后在用户输入内容后启用它?

有可能吗?如果没有,还有其他方法吗?

谢谢

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,但为了这个简单的目的,应该使用 workarount 来完成这项工作。

代码:

onChanged: (value) { setState(() { _newMessage = value; if(_newMessage.length > 0){ //add these lines isInputEmpty = false; } else { isInputEmpty = true; } }); }, 之前初始化一个新的 bool isInputEmpty

IgnorePointer(
          ignoring: isInputEmpty,child: IconButton(...),),

并且要禁用按钮,您可以将他包裹在 IgnorePointer

IconButton(
          color: isInputEmpty ? Colors.grey : Colors.tealAccent,

您甚至可以更改按钮颜色:

struct List {
    std::list<Term> terms;
    int number;
};