Create Random Colours in Flutter

Manav SarkarManav Sarkar
2 min read

Choosing a colour from a wide range of Colours is sometimes time-consuming. Also during debugging, we may need to generate random colours for different purposes. A good example would be we want different colours for notes application. So we can generate different colours using just some code.

Syntax

Using Color.fromRGBO( int r, int g, int b, double opacity)

This method takes 4 parameters as follows:

  • r - r is used for red colour and ranges from 0-255.

  • g - g is used for green colour and ranges from 0-255.

  • b - b is used for blue colour and ranges from 0-255.

  • opacity: The opacity of colour ranges from 0-1 in double data type.

This method generates colour as RGB and takes a parameter for opacity. We can generate random numbers using the Random() method of the dart math library. So the syntax will be as follows.

Color rand_color = Color.fromRGBO(
  math.Random().nextInt(255),
  math.Random().nextInt(255),
  math.Random().nextInt(255),
  math.Random().nextDouble(),
);

Using Color.fromARGB( int a, int r, int g, int b)

This also takes four parameters where r,g,b means the same while a used for the alpha that is similar to the opacity but it takes an integer value from 0-255.

The syntax is as follows.

Color colorARGB = Color.fromARGB(
    math.Random().nextInt(255),
    math.Random().nextInt(255),
    math.Random().nextInt(255),
    math.Random().nextInt(255),
  );

This method generates colour as RGB and takes a parameter for opacity. We can generate random numbers using the Random() method of the dart math library. So the syntax will be as follows.

Color rand_color = Color.fromRGBO(
  math.Random().nextInt(255),
  math.Random().nextInt(255),
  math.Random().nextInt(255),
  math.Random().nextDouble(),
);

Using Color.fromARGB( int a, int r, int g, int b)

This also takes four parameters where r,g,b means the same while a used for the alpha that is similar to the opacity but it takes an integer value from 0-255.

The syntax is as follows.

Color colorARGB = Color.fromARGB(
    math.Random().nextInt(255),
    math.Random().nextInt(255),
    math.Random().nextInt(255),
    math.Random().nextInt(255),
  );

0
Subscribe to my newsletter

Read articles from Manav Sarkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manav Sarkar
Manav Sarkar