【问题标题】:Flutter Disable and Enable Button based on the user input on textfield基于文本字段上的用户输入的颤振禁用和启用按钮
【发布时间】:2021-07-15 18:20:18
【问题描述】:

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

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

谢谢

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,
        ),
      ],
    );

【问题讨论】:

    标签: flutter button textfield


    【解决方案1】:

    要实现这一点,您必须从文本字段中获取输入的长度,正确的方法是使用 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,
    ),
    

    【讨论】:

      【解决方案2】:

      使用文本编辑控制器https://flutter.dev/docs/cookbook/forms/text-field-changes

      final controller = TextEditingController();
       onPressed: controller.text.length==0 ? null :  _sendNewMessage,
      

      请检查.length是否正确不记得了哈哈

      【讨论】:

      • 谢谢,我接受了第一个答案,但我仍然尝试了你的答案,它也有效
      猜你喜欢
      • 2021-04-24
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      相关资源
      最近更新 更多