Flutter中如何避免TextField内容为空时触发onChanged执行计算
问题根因
输入框清空后int.tryParse('')会返回null,你的计算函数直接对null执行算术运算,就触发了控制台的NoSuchMethodError异常。
方案1:满足清空时阻止计算函数调用的需求
修改TextField的onChanged回调逻辑,仅当输入内容非空时才执行计算:
Expanded( child: Column( children: [ TextField( focusNode: _bigBlindFocusNode, keyboardType: TextInputType.number, onChanged: (text) { // 去掉首尾空白后判断是否非空,再触发计算 if (text.trim().isNotEmpty) { setState(() { _calculateTotalPotPreflop(); }); } }, controller: _textEditControllerBigBlind, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Big Blind', ), ) ], ) )
方案2:额外优化计算函数(推荐补充,避免其他输入框为空时报错)
就算触发计算,也给所有输入转换结果增加空值兜底,为空时默认取0,同时修正原代码中打印逻辑先于计算的问题:
_calculateTotalPotPreflop() { // 所有输入值做空值兼容,为空默认取0 int smallBlind = int.tryParse(_textEditControllerSmallBlind.text) ?? 0; int bigBlind = int.tryParse(_textEditControllerBigBlind.text) ?? 0; int ante = int.tryParse(_textEditControllerAnte.text) ?? 0; int playerCount = int.tryParse(_textEditControllerNumberPlayers.text) ?? 0; if (_bigBlindAnteCheckbox == true) { totalPotPreflop = smallBlind + bigBlind + ante; } else { totalPotPreflop = smallBlind + bigBlind + (playerCount * ante); } // 计算完成后再打印结果 print("total pot: ${totalPotPreflop.toInt()}"); }
内容的提问来源于stack exchange,提问作者kevin
相关产品推荐
相关产品推荐

