Search code examples
androidflutterdarthttpapi

Remapping values from min/max to max/min in Dart / Flutter


I am developing an application in Flutter via the Dart programming language. I am trying to control an RGB-LED via HTTP-API call. The problem im having is, that the LED is inverted in its properties. Im not an expert in this topic but i can provide you with the following information: When setting the r, g and b values for the LED, each of them require an integer ranging from 0 to 255. These values get send to the LED via URL query parameters. The probem is, that the LED shuts down the pins when the value is 255 and turns them fully on if the value is 0. Since color pickers get the value in the opposite order (meaning that full red is 255 and no red is 0) i need to somehow remap a 0 to 255 and vice versa. Also each value between 0 and 255 needs to be remapped, meaning that a 254 would need to be a 1 for example. Any help would be greatly appreciated.


Solution

  • This is a mathematical problem, and quite easy i think.

    Since you know the hardcoded values you need, and the limit [no bigger than 255]

    you need

    255 -> 0

    254 -> 1 //not 2 -.-

    10 -> 245

    You could add a substraction

    255 - 255 = 0

    255 - 254 = 1

    255 - 10 = 245

    and code a simple function like

    int invertNumber(int initialNumber){
        return 255 - initialNumber;
    }
    

    and call it like

    int invertedNumber = invertNumber(40);