我在 flutter 中有以下声明。 weight
是来自 _weightController 的文本,即 _weightController.text
int.parse(weight).toString().isNotEmpty && int.parse(weight) > 0
但是在 Dart 2.0 中它不能正常工作。对于空的 TextField,它给出了错误。
====== Exception caught by gesture ==============================
The following FormatException was thrown while handling a gesture:
Invalid number (at character 1)
代码块是这样的。
if (int.parse(weight).toString().isNotEmpty && int.parse(weight) > 0)
return int.parse(weight) * multiplier;
else
print('Error');
最佳答案
作为其他答案的替代方法,您可以使用 tryParse() method :
Like parse except that this function returns null where a similar call to parse would throw a FormatException, and the source must still not be null.
如果你使用这种方法,你应该检查返回值是否为 null:
String weight ="";
int number = int.tryParse(weight);
if (number !=null){
print(number );
}
else
print("error");
不要忘记使用
weight ? ""
检查变量是否为空。或与 weight != null
关于flutter - 使用 null 改写 Dart 2.0 中的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61120114/