How to handle invalid value: valid value range is empty using ? operator

二次信任 提交于 2021-02-11 18:20:01

问题


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];
}

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;

回答1:


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;
}

and now you should be able to do

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


来源:https://stackoverflow.com/questions/61284067/how-to-handle-invalid-value-valid-value-range-is-empty-using-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!