What is the best practice to return null for:
Unhandled exception: RangeError (index): Invalid value: Not in inclusive range 0..2
My code:
late final int? element;
try {
element = l[index];
} catch(e) {
element = null;
}
Looking for a shorter, one-liner solution.
Something like:
final element = l[index] ?? null;
CodePudding user response:
The best practice for errors is to not throw them.
In this case, I'd do:
final T? element = (index >= 0 && index < l.length) ? l[index] : null;
No need for late
, not throwing or catching errors.
If an error does get thrown, it's probably a real error in the program.
CodePudding user response:
Hope this answer can satisfy you. :)
final int? element = (index == null || index.clamp(0,l.length - 1) != index) ? null : l[index];
CodePudding user response:
you can use extension method :
myextension.dart :
extension NullableList<T> on List<T> {
T? nullable(int index){
T? element;
try {
element = this[index];
} catch(_) {
}
return element;
}
}
use it :
homepage.dart :
List<int> l = [1];
int? result = l.nullable(3);
print(result); //--> null
print(l.nullable(0)); //--> 1