flutter - 使用 List.length 时 Dart 断言不起作用

标签 flutter dart

我想在初始化类时检查列表长度。 我尝试过,但它没有按预期工作。 我的代码在这里。

@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

enter image description here

如何让它按预期运行?

编辑 1

现在断言不再有效。 enter image description here

编辑2

enter image description here

编辑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

enter image description here

编辑6

enter image description here

最佳答案

我没有足够的声誉来添加评论,所以我会将其添加为答案。

显然,这正在按预期工作。找到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 the length getter run arbitrary code, and still have a const constructor in MyList, 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 a List or List<T> for some T is specified.

不确定是否有办法解决这个问题,但我希望这会有所帮助。

关于flutter - 使用 List.length 时 Dart 断言不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74080929/

相关文章:

flutter - StreamBuilder 没有重新渲染里面的小部件?

flutter - 制作新小部件后清除类(class)列表

dart - 在Flutter中正确使用媒体查询

flutter - NoSuchMethodError : The getter 'status' was called on null on flutter

flutter - 如何解决 "RangeError (index): Invalid value: Only valid value is 0: 1"错误

Flutter:使用自定义函数保存从预览页面生成的 PDF

android - 抖动错误: Exception: type 'int' is not a subtype of type 'String'

listview - 插入新记录后如何重新加载列表?

list - Dart中两种类型的List初始化之间的区别

dart - Dart 中的替代方法(例如JAVA)