dart - 为什么在空安全的Dart中使用 'var'声明的变量为空?

标签 dart dart-null-safety

我正在从docs复制此文件

// In null-safe Dart, none of these can ever be null.
var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();
但是我正在null-safe dartpad中运行以下代码,并且可以编译。
void main() {
  var x = null;
  print(x);
}
这是文档错误还是我缺少什么?

最佳答案

您的示例与文档试图解释的内容不太接近。尝试以下方法:

void main() {
  var x = 42;
  x = null; // Error: A value of type 'Null' can't be assigned to a variable of type 'int' - line 3
  print(x);
}
原因是var x = 42是“推断为int”,而不是int?
在您的示例中,发生的事情是var x = null已解析,因此x被视为dynamic类型,因为Dart不知道您要使用哪种类型。由于dynamic可以具有值null,因此您可以使用。

关于dart - 为什么在空安全的Dart中使用 'var'声明的变量为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64281775/

相关文章:

android - 如何在 flutter 中使下拉项的宽度大于容器(下拉按钮)

json - 在 jaguar_serializer 中运行 'serializer build' 时出错

firebase - 我想从 flutter 中数组内部的 map 中读取数据

Dart null safety : the operand cannot be null, 所以条件总是为真

json - Flutter 迁移到 null 安全性,是迟到还是可为 null?

dart-null-safety - 错误: The argument type 'List<int>' can't be assigned to the parameter type 'Uint8List'

firebase - 在 org.gradle.api.Project 类型的项目 ':app' 上找不到参数 [] 的方法 Properties()

flutter - 我试图创建将数字作为输入的TextFormFields列表,我想对所有这些数字求和

dart - 如果在声明时初始化,为什么我们不能更改变量值?

dart - late 和 final 可以一起用吗?