我想在初始化类时检查列表长度。 我尝试过,但它没有按预期工作。 我的代码在这里。
@immutable
class TestClass {
const TestClass(this.values)
: assert(values.length >= 0 && values.length <= 4);
final List<int> values;
}
const a = TestClass(<int>[1, 1, 1]); // assert
如何让它按预期运行?
编辑 1
编辑2
编辑3
// OK
final ok = TestClass(const <int>[1]);
// NG
final ng = TestClass(const <int>[1, 1, 1, 1, 1]);
编辑4
@immutable
class TestClass2 {
const TestClass2(
this.value,
) : assert(value.length == 3);
final String value;
}
final a = TestClass2('abcde');
我认为 T.length
在断言中不起作用。
编辑5
编辑6
最佳答案
我没有足够的声誉来添加评论,所以我会将其添加为答案。
显然,这正在按预期工作。找到this issue Dart SDK 存储库上有类似的内容。在评论中有人referenced以下来自语言规范:
You cannot get the length of a list in a constant expression. The language specification says so here:
\item An expression of the form \code{$e$.length} is potentially constant if $e$ is a potentially constant expression. It is further constant if $e$ is a constant expression that evaluates to an instance of \code{String}.
So it must be rejected at compile-time. This is one of many situations where it's tempting to make Dart constant expressions just a little bit more expressive, but it is quite costly (in so many ways) so it's not very likely to happen. One issue is that you can write a
class MyList extends List<String> {...}
and make thelength
getter run arbitrary code, and still have aconst
constructor inMyList
, and constant expressions will not run arbitrary code, so you'd need to find the right borderline between the lists where.length
is OK and the lists where it isn't, and the type system wouldn't be able to prevent the latter from occurring where aList
orList<T>
for someT
is specified.
不确定是否有办法解决这个问题,但我希望这会有所帮助。
关于flutter - 使用 List.length 时 Dart 断言不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74080929/