An implementation for the “Arduino map” function in Dart, which allows numbers to be remapped from one range to another.
Re-maps a number from one range to another. That is, a value of
get mapped to
toLow, a value of
toHigh, values in-between to values
Does not constrain values to within the range, because out-of-range values are
sometimes intended and useful. Use the
remapAndClamp method if you wish for
the values to be constrained.
Note that the “lower bounds” of either range may be larger or smaller than the
“upper bounds” so the
remap() method may be used to reverse a range of numbers,
final reversedX = x.remap(1, 50, 50, 1);
The method also handles negative numbers well, so that this example
final y = x.remap(1, 50, 50, -100);
is also valid and works well.
remap, however the result is being constrained to the range
For instance, the following code returns
150.remapAndClamp(0, 100, 0, 1)
toLow may be greater than
toHigh, so the following code
final y = x.remapAndClamp(0, 100, 100, 0);
remap and the
remapAndClamp offer integer-only versions of themselves (named
remapAndClampInt respectively). These work the same as their
num counterparts, however their return value is guaranteed to be an integer.
Returns whether a number is within a given range.
- Add the package as a dependency to your
- Import the library:
The library acts as an extension to the
int types. You can use its methods as follows:
import 'package:num_remap/num_remap.dart'; ... final someDouble = 0.5; final remappedDouble = someDouble.remap(0.0, 1.0, -100.0, 100.0);