Home > other >  Dart best practice to return null from RangeError (index)
Dart best practice to return null from RangeError (index)

Time:12-02

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
  •  Tags:  
  • dart
  • Related