本文介绍了如何处理无效值:有效值范围为空?操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var items = [];
var index = 0;
var value = items[index]; // returns invalid value error, understood!

我宁愿使用以下代码来防止错误

I should rather use following to prevent the error

if (index < items.length) {
  value = items[index];
}

由于Dart中有?个运算符,所以我想知道有什么方法可以做类似的事情:

Since there are ? operators in Dart, I wanted to know is there any way I can do something like:

var value = items?.[0] ?? -1; 
var value = items?[0] ?? -1;

推荐答案

否.?用于识别 null 的运算符(或用于三元运算符).访问 List 的无效元素会引发异常,而不是返回null,因此,了解null的运算符将无济于事.

No. ? is used to for null-aware operators (or for the ternary operator). Accessing an invalid element of a List throws an exception instead of returning null, so null-aware operators won't help you.

如果愿意,可以添加一个辅助函数并使它作为扩展更为方便:

If you like, you could add a helper function and make it more convenient as an extension:

extension ListGet<E> on List<E> {
  E get(int index, [E defaultValue]) =>
      (0 <= index && index < this.length) ? this[index] : defaultValue;
}

现在您应该可以了

var value = items.get(0, -1);

这篇关于如何处理无效值:有效值范围为空?操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 18:52