问题
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