为什么在Dart的null安全中无法访问List()构造函数? [英] Why List() constructor is not accessible in Dart's null safety?

查看:60
本文介绍了为什么在Dart的null安全中无法访问List()构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NNBD,不允许使用默认构造函数初始化列表:

With NNBD, you're not allowed to initialise the list using the default constructor:

List<int> foo = List(); // Compile time error

但是,您仍然可以:

List<int> foo = []; // No error

那么,两者之间有什么区别?它们要么都不显示错误,要么都不显示.

So, what's the difference between the two? Either both of them should show the error or none of them.

推荐答案

List 构造函数有两种用途:

The List constructor had two uses:

  • new List()创建一个空的可增长列表,等效于 [] .
  • 新列表(n),以创建长度为 n 的固定长度列表,并填充 null
  • new List() to create an empty growable list, equivalent to [].
  • new List(n) to create a fixed-length list of length n filled with null values

出于安全考虑,大多数情况下第二次使用都是不安全的,并且没有很好的方法来修复它.可以将类型参数强制为不可为空,但是 List< T>(4)仅在 T nullable 时有效.没有办法强制执行.

With null safety, the second use was unsound most of the time, and there was no good way to fix it. It's possible to force a type argument to be non-nullable, but List<T>(4) only works when T is nullable. There is no way to enforce that.

因此,需要进入 List(n)模式(由 List.filled(n,value)取代,这迫使您提供填充值).剩下的 List()并没有真正发挥自己的作用.您可以改为使用 [] (并且 应该 !),因此决定完全删除该构造函数-对其的所有使用都不安全或无用.(此外,它已经是一个奇怪的构造函数,因为如果我们想使其正确为null安全,它将有一个带有非空类型且没有默认值的可选参数.)

So, the List(n) mode needed to go (replaced by List.filled(n, value) which forces you to provide a fill-value). That left List(), which doesn't really carry its own weight. You can just use [] instead (and you should!), so it was decided to remove the constructor entirely - all uses of it was either unsafe or useless. (Also, it was a weird constructor already, because if we wanted to properly make it null safe, it would have an optional parameter with a non-nullable type and no default value.)

通过完全删除它,有可能在将来引入新的 List 构造函数,也许作为 List.filled 的较短别名.一个人可以希望.

By removing it completely, it makes it possible to, potentially, introduce a new List constructor in the future, perhaps as a shorter alias for List.filled. One can hope.

这篇关于为什么在Dart的null安全中无法访问List()构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆