Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

dart - The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'

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(); 

However, you can still do:

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

use the following:

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

Long answer:

The List constructor had two uses:

  • 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

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.

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.)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...