Flutter - How to change color of marker based on magnitude of an int?

I want to create markers at each GPS point with a color on a scale from white to red that corresponds to how slow or fast the GPS data indicates the speed is at that point. However, since Color.fromRGBO() requires const arguments, I'm having trouble getting the speed to change the color. How could I circumvent the Color class or find a better way to draw such a gradient than with Marker objects?

1 answer

  • answered 2022-05-07 05:26 tahesse

    Welcome to StackOverflow Onur!

    You can indeed use https://api.flutter.dev/flutter/dart-ui/Color/Color.fromARGB.html

    const Color.fromARGB(
        int a,
        int r,
        int g,
        int b

    with a=0, g=0 and b=0 and use your scale (you need to know the maximum value, lets call it r_max, to normalize the range). So whenever you have an intensity value, lets call it r_intensity, you'd simply compute

    const r = 255 * (r_intensity / r_max)

    to compute your color intensity. The result of r_intensity / r_max will always be in range [0, 1] multiplied by 255 to conform with

    r is red, from 0 to 255. from the docs.

    Regarding the const issue: it sounds like you want to (heavily?) animate the color. Look at https://api.flutter.dev/flutter/animation/AnimationController-class.html and set the red color value to your Widgets state.

    Other than that, it should work to either have

    1. a method that returns the new red value (and does the aforementioned computation)
    2. simply use var r = ... instead of const r = ... and pass it to Color

    EDIT: looking at your image, the issue might stem from your int being null. Please make sure that your Color Widget is not wrapped into any Widget prefixed with const! This will likely be the case here and produces the result you are seeing. Tested it on my side to confirm.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum