Easily check if a number is in a given Range in Dart?

Quite simply, no. Just use 1 <= i && i <= 10.


Since the inclusion of extension functions, this answer could be changed slightly if you are okay with doing the checks non-inline.

To my knowledge, there is no built in functions for this, but you could easily create your own extension on num to simulate this.

Something like this would simulate a range verification:

void main() {
  final i = 2;
  if (i.isBetween(1, 10)) {
    print('Between');
  } else {
    print('Not between');
  }
}

extension Range on num {
  bool isBetween(num from, num to) {
    return from < this && this < to;
  }
}

This method in particular is exclusive both from and to, but with minor tweaking and better naming you could easily create extension functions for all of the Kotlin range checks.

Tags:

Dart