【问题标题】:Dart is null check on List entry throws range errorDart 对 List 条目进行 null 检查会引发范围错误
【发布时间】:2020-01-05 13:58:01
【问题描述】:

我已经初始化了一个空列表,并想检查该条目是 true 还是 null。由于我实际上无法首先使用 false 填充每个条目,因此我需要检查它是 null 还是 true。

List<bool> check = List<bool>();

我是否使用:

(check[index]) ? dothis : dothat;

或:

(check[index] != null) ? dothis : dothat;

他们都抛出一个范围错误。因为我不能像这样初始化它

List<bool> check = [false,false,false,false,false forever and ever];

我该如何解决这个问题?

【问题讨论】:

  • 您要解决的实际问题是什么?您无法访问不存在的列表的索引。也许改用一套? Set&lt;int&gt; chek = {}; ... check.contains(index) ? dothis : dothat.

标签: list flutter dart


【解决方案1】:

因为我不能像这样初始化它

List&lt;bool&gt; check = [false,false,false,false,false forever and ever];

在我看来,您想要一个稀疏填充的List。如果是这样,只需使用Map&lt;int, T&gt; 而不是List&lt;T&gt;。如果项目尚未添加,check[index] 将返回 null

var check = <int, bool>{};
...
(check[index] ?? false) ? dothis : dothat;

bool 的情况下,使用Set&lt;int&gt; 并只检查存在而不是维护单独的bool 值会更好:

var checked = <int>{};
...
checked.contains(index) ? dothis : dothat;

【讨论】:

  • 是的,最好的答案是使用带有简单整数列表的checked.contains(index) ? dothis : dothat;。这就是我最后所做的。布尔不是这里的路。
【解决方案2】:
List<bool> check = [];

if (check.length > index) {
  // you are safe to perform anything like check[index]
}

更新:

color: check.length > index ? (check[index] ? Colors.blue : Colors.grey) : Colors.white

更新2:

不知道为什么你说它不工作,我给你一个build() 方法,你可以尝试注释掉其他代码,看看它工作。

Widget build(BuildContext context) {
  var check = [true];
  int index = 5;

  return Scaffold(
    appBar: AppBar(),
    body: Container(
      width: 100,
      height: 100,
      color: check.length > index ? (check[index] ? Colors.blue : Colors.grey) : Colors.white,
    ),
  );
}

【讨论】:

  • 但由于它是 Flutter,它实际上不会让我在这个地方使用 if。它是小部件中颜色的参数。这就是我使用三元运算符的原因。是否没有 null 感知检查?
  • 很抱歉我没听明白,你能把代码显示在你想用的地方吗?
  • 就像colour: (check[index]) ? Colors.blue : Colors.grey; 这样你不能在那里使用if
  • 这实际上是行不通的。如果我将任何值设置为 true,那么它会再次引发范围错误。仅当列表为空时才有效。
  • 这根本行不通,因为如果索引条目 6 为真,那么长度为 1,但 0 处的值为假,因此它仍会引发范围错误。仅当列表为空时才有效。
【解决方案3】:

在获取值之前检查索引是否存在。

List<bool> check = List<bool>();

if(index <= (check.length - 1)) {
  (check[index]) ? dothis : dothat;
}


OR

(index < check.length) 
                       ? (check[index]) ? Colors.blue : Colors.red
                       // return default color
                       :  Colors.white

这样的事情应该可以工作!

【讨论】:

  • 但由于它是 Flutter,它实际上不会让我在这个地方使用 if。它是小部件中颜色的参数。这就是我使用三元运算符的原因。
  • 天哪,我只是在等待那些超长的三元运算符之一。是的,这当然行得通。我不明白为什么 Dart 没有像 firstOrNull 这样的东西。
  • 这实际上是行不通的。如果我将任何值设置为 true,那么它会再次引发范围错误。仅当列表为空时才有效。
  • 这根本行不通,因为如果索引条目 6 为真,那么长度为 1,但 0 处的值为假,所以它仍然会引发范围错误。
  • 试试check[5] = true;,它会抛出同样的范围错误,因为长度为1,但第一个条目是空的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
相关资源
最近更新 更多