启用空安全时,默认的“列表"构造函数不可用.尝试使用列表文字,“List.filled"或“List.generate" [英] The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'

查看:29
本文介绍了启用空安全时,默认的“列表"构造函数不可用.尝试使用列表文字,“List.filled"或“List.generate"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么List()构造函数在Dart的空安全后不可访问?

Why List() constructor is not accessible after Dart's null safety?

// Compile time error: 'List' is deprecated and shouldn't be used.
// The default 'List' constructor isn't available when null safety is enabled. 
// Try using a list literal, 'List.filled' or 'List.generate'.
List<int> foo = List(); 

但是,您仍然可以:

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.

推荐答案

简答:

代替前空安全操作

Short answer:

Instead of the pre-null-safety operations

var foo = List<int>();  // Now error
var bar = List<int>(n); // Now error
var baz = List<int>(0); // Now error

使用以下内容:

var foo = <int>[];           // Always the recommended way.
var bar = List.filled(1, 0); // Not filled with `null`s.
var baz = List<int>.empty();

长答案:

List 构造函数有两个用途:

Long answer:

The List constructor had two uses:

  • new List() 创建一个空的可增长列表,相当于[].
  • 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

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

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() 并没有真正承载其自身的重量.您可以使用 [] 代替(并且您 应该!),因此决定完全删除构造函数 - 它的所有用途要么不安全,要么无用.(此外,它已经是一个奇怪的构造函数,因为如果我们想正确地使其为空安全,它将有一个可选参数,该参数具有不可为空的类型且没有默认值.)

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.

这篇关于启用空安全时,默认的“列表"构造函数不可用.尝试使用列表文字,“List.filled"或“List.generate"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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