Is there an operator or function in Dart to easily verify if a number is in a range? Something like Kotlin in
operator:
https://kotlinlang.org/docs/reference/ranges.html
if (i in 1..10) { // equivalent of 1 <= i && i <= 10
println(i)
}
Dart numbers (the type num ) are either integers (type int ) or doubles (type double ). It is easy to check if a number is an int , just do value is int .
To check whether a string is a numeric string, you can use the double. tryParse() method. If the return equals null then the input is not a numeric string, otherwise, it is.
The Double data type in Dart represents a 64-bit (double-precision) floating-point number. For example, the value "10.10". The keyword double is used to represent floating point literals.
Dart numbers can be classified as: The int data type is used to represent whole numbers. The double data type is used to represent 64-bit floating-point numbers. The num type is an inherited data type of the int and double types.
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.
I find using clamp more readable. So, to check if i is between 1 and 10, clamp it to the range and compare to itself.
if (i.clamp(1,10) == i) {
print(i);
}
Documentation for clamp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With