Flutter – Generate random color

In this post we will show you a couple of ways to generate random color in Flutter. You may find many existing packages to get this done on pub.dev. In this post, let’s do it manually.

1. Generate random color from a list of predefined colors

Color generateRandomColor1() {
  // Define all colors you want here
  const predefinedColors = [
    Colors.red,
    Colors.green,
    Colors.blue,
    Colors.black,
    Colors.white
  ];
  Random random = Random();
  return predefinedColors[random.nextInt(predefinedColors.length)];
}


2. Generate random color using Color(int) constructor and random double (0.0 to 1.0)

Color generateRandomColor2() {
  Random random = Random();
  // Pick a random number in the range [0.0, 1.0)
  double randomDouble = random.nextDouble();

  return Color((randomDouble * 0xFFFFFF).toInt()).withOpacity(1.0);
}


3. Generate random color using Color.fromARGB() constructor and random integers

Color generateRandomColor3() {
  Random random = Random();

  return Color.fromARGB(
      255,
      random.nextInt(256),
      random.nextInt(256),
      random.nextInt(256));
}

void main() {
  print(generateRandomColor1());
  print(generateRandomColor2());
  print(generateRandomColor3());
}

flutter: Color(0xff000000)
flutter: Color(0xff060364)
flutter: Color(0xff40868d)

Tagged : / /
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x