The concept is getting a single random color and change hue to generate others based on this color. For this, we can use HSLColor system
/// return new [color] hue change by [increaseBy]
Color changeColorHue({
required Color color,
required double increaseBy,
}) {
HSLColor hslColor = HSLColor.fromColor(color);
final newHueValue = (increaseBy + hslColor.hue);
return hslColor
.withHue(
newHueValue % 360 < 0 ? newHueValue : newHueValue % 360,
)
.toColor();
}
Now get a random from bellow and use pass color and hue like to increase.
The concept of using Set
of 3 works perfectly in this case. Got idea from comment section.
Random color from original Question
Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0)
Or from primary colors
Colors.primaries[Random().nextInt(Colors.primaries.length)],
The method will return a color set.
Set<Color> getColorSet({int numberOfColor = 3}) {
Set<Color> generatedColorSet = Set<Color>();
while (generatedColorSet.length != numberOfColor) {
generatedColorSet.add(
Colors.primaries[Random().nextInt(Colors.primaries.length)],
);
////* from primary colors
// generatedColorSet.add(
// Colors.primaries[Random().nextInt(Colors.primaries.length)],
// );
}
return generatedColorSet;
}
Get a random color
Test widget
class ColorTESt extends StatefulWidget {
ColorTESt({Key? key}) : super(key: key);
@override
State<ColorTESt> createState() => _ColorTEStState();
}
class _ColorTEStState extends State<ColorTESt> {
Set<Color> colorSet = Set<Color>();
@override
void initState() {
super.initState();
colorSet = getColorSet();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(colorSet.elementAt(0)),
overlayColor: MaterialStateProperty.all(colorSet.elementAt(1)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
side: BorderSide(
color: colorSet.elementAt(2),
width: 3,
),
),
),
),
onPressed: () {
setState(() {
colorSet = getColorSet();
});
},
child: Text(
"generate New color Set",
style: TextStyle(color: Colors.white),
),
),
);
}
}