How can i use random color in colors array(not in single color) in flutter

Issue

If we need a random color for single color,
There are lot of methods
like

 color: Color(Random().nextInt(0xffffffff)).withAlpha(0xff);
 color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
 color: Colors.primaries[Random().nextInt(Colors.primaries.length)],

If i use the above color code in colors array it shows error,

but i want to use random color in colors array

like

              colors: <Color>[
                      randomColor,
                      randomColor,
                      randomColor,
                    ],

My full code

 Ink(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    colors: <Color>[
                      Colors.blue,
                      Colors.red,
                      Colors.green,
                    ],
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(80.0)),
                ),
),

Please help someone. Thanks in advance.

Solution

The colors you defined are not constant

 color: Color(Random().nextInt(0xffffffff)).withAlpha(0xff);
 color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
 color: Colors.primaries[Random().nextInt(Colors.primaries.length)],

That’s why you get the error in LinearGradient since you declared your BoxDecoration as constant.

Evaluation of this constant expression throws an exception

To fix your issue just omit the const right before BoxDecoration.

Ink(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: <Color>[
                randomColor,
                randomColor,
                randomColor,
              ],
            ),
            borderRadius: const BorderRadius.all(Radius.circular(80.0)),
          ),
        ),

Answered By – quoci

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.