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

标签 flutter dart

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

相关文章:

flutter - "$ flutter build web"抛出错误 "Missing index.html"?

android - 在 Android 版本 11 上面临 flutter 错误

flutter - 当Flutter中的全局变量更改(异步)时更新小部件

firebase - Flutter - 从 firestore 循环获取数据

flutter - 如何在 FLUTTER 中几秒钟后重定向到 Stream Builder 中的另一个屏幕/页面?

android - flutter - 如何延迟到ListView,所以项目一个一个显示

flutter - 无法从Firestore文档中删除字段(Flutter)

flutter - Flutter/pubspec.yaml 中的版本号问题

ios - Flutter 在执行 Flutter build ios 后卡在 Building Dart 代码上

dart - 如何在Dart中将数据从实用程序类传递到主类