Home > Enterprise >  How to randomly change rgb color?
How to randomly change rgb color?

Time:07-12

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),
        ),
      ),
    );
  }
}

CodePudding user response:

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),
        ),
      ),
    );
  }
}

CodePudding user response:

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)]
  • Related