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),
);
Example
In the following example, we have two buttons which when clicked generate random colours.
Code
import 'package:flutter/material.dart';
import 'dart:math' as math;
class GenerateRandomColours extends StatefulWidget {
const GenerateRandomColours({Key? key}) : super(key: key);
@override
_GenerateRandomColoursState createState() => _GenerateRandomColoursState();
}
class _GenerateRandomColoursState extends State<GenerateRandomColours> {
Color colorRGBO = Color.fromRGBO(
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextDouble(),
);
Color colorARGB = Color.fromARGB(
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextInt(255),
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Generate Random Colours"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
Color randColor = Color.fromRGBO(
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextDouble(),
);
setState(() {
colorRGBO = randColor;
});
},
child: const Text("Using Color.fromRGBO"),
style: ElevatedButton.styleFrom(
primary: colorRGBO,
),
),
ElevatedButton(
onPressed: () {
Color randColor = Color.fromARGB(
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextInt(255),
math.Random().nextInt(255),
);
setState(() {
colorARGB = randColor;
});
},
child: const Text("Using Color.fromARGB"),
style: ElevatedButton.styleFrom(
primary: colorARGB,
),
),
],
),
),
);
}
}
Output
