gpt4 book ai didi

flutter - 使用 null 改写 Dart 2.0 中的 if 语句

转载 作者:行者123 更新时间:2023-12-03 04:23:38 27 4
gpt4 key购买 nike

我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com