文本字段onChanged(){setstate}无法正常工作

时间:2020-10-11 01:35:13

标签: flutter textfield setstate

当用户在文本字段上键入至少一个字符时,我想更改按钮的颜色 也想在文本字段为空时更改颜色

所以我试图标记(布尔值)来实现

onChanged: (value) {
    if (value.length == 0) {
      setState(() {
        _isTimeFilled = false;
      });
    } else {
      setState(() {
        _isTimeFilled = true;
      });
    }
},

...

_isFilled ? Colors.grey : Colors.green

但是它只会在文本框未聚焦时更改颜色

我也尝试过提供程序,但这是相同的。 我该如何解决?

这是我的代码

    void _changeButtonColor(int value) {✅✅✅✅
    if (value == 0) {
      setState(() => _isTimeFilled = false);
    } else {
      setState(() => _isTimeFilled = true);
    }
  }
  
    TextFormField TimeTextFormField() {
    return TextFormField(
      focusNode: timeFocusNode,
      autofocus: true,
      keyboardType: TextInputType.number,
      textInputAction: TextInputAction.next,
      onChanged: (value) {
        _changeButtonColor(value.length);✅✅✅✅
      },
      
      
      RaisedButton(
            focusColor: Colors.white,
            splashColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(6.0),
            ),
            onPressed: () {},
            color: _isTimeFilled ? Colors.greenAccent : Colors.grey, ✅✅✅✅
            textColor: Colors.white,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SizedBox(
                  width: double.infinity, child: Icon(Icons.check)),
            ),
          ),
        ),

3 个答案:

答案 0 :(得分:1)

执行此操作:

onChanged: (value) {
    _isTimeFilled = (value != 0);
    setState(() { });
},

答案 1 :(得分:1)

TextField的onChanged是作为参数的字符串。 并且,_isFilled和_isTimeFilled需要统一。

所以

onChanged: (value) {
  if (value.length <= 0) {
    setState(() {
      _isFilled = false;
    });
  } else {
    setState(() {
      _isFilled = true;
    });
  }
},

答案 2 :(得分:0)

找到了解决方案,但不知道确切原因 刚刚做到了

原因:我尝试使用方法在bottomSheet中弄清楚

解决方案:制作稳定的小部件并调用它。

EX my code 

floatingActionButton: FloatingActionButton(
        onPressed: () {
          showCupertinoModalBottomSheet(
            context: context,
            builder: (context, scrollController) => inputForms(),
          );
        },

inputForms是返回表单字段的方法<我不好,我不在乎状态>

======

解决方案:使表单字段成为稳定的小部件并导入

      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showCupertinoModalBottomSheet(
            context: context,
            builder: (context, scrollController) => StatefulFormFields(),
          );
        },

感谢您的回答?

相关问题