How to randomly change rgb color?

Viewed 80

In the application, when you click on the screen, you need to change the color to random, but it must be in RGB format. How can I get a random RGB color?

class _HomePageState extends State<HomePage> {
  Color _color = Colors.white;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Color picker"),
        centerTitle: true,
      ),
      body: GestureDetector(
        onTap: () {
          setState(() {
            _color = ...
          });
        },
        child: Container(
          color: _color,
          padding: const EdgeInsets.all(20),
        ),
      ),
    );
  }
}

3 Answers

You can do like this

class _HomePageState extends State<HomePage> {
    
       Random random = Random();
  Color _color = Colors.white;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Color picker"),
        centerTitle: true,
      ),
      body: GestureDetector(
        onTap: () {
          setState(() {
            _color = Color.fromRGBO(
              random.nextInt(255),
              random.nextInt(255),
              random.nextInt(255),
              1,
            );
          });
        },
        child: Container(
          color: _color,
          padding: const EdgeInsets.all(20),
        ),
      ),
    );
  }
}

Best wat to get a random color:

Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0)

This import is required.

import 'dart:math' as math;

or

Colors.primaries[Random().nextInt(Colors.primaries.length)]

The other solutions (so far) are literally creating an arbitrary RGB value as requested, but I suspect the OP wants a "different but workable color". Random RGB is a poor way to generate those. You want randomness in the HSV direction.

In that case, supply random values to HSVColor.fromAHSV. Alpha should be 1.0 (opaque). Hue can be anything from 0.0 to 360.0. Saturation should probably be between 0.5 and 1.0 (more color than grey). Value should be between 0.0 and 0.5 if you have contrasting light text, and 0.5 to 1.0 if you have contrasting dark text.

Related