84

Generate random colors

return new RaisedButton(


    padding:  EdgeInsets.symmetric(vertical: 30.0),
    color: Colors.primaries random  List <blue,green>,
Dev Ed
  • 831
  • 2
  • 11
  • 23

15 Answers15

197

This is my way to get a random color:

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

Note:
This import is required.

import 'dart:math' as math;
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
Ascension
  • 2,599
  • 2
  • 15
  • 13
94

There is an in-built list of material colors in the Colors class. You can use it like below

var generatedColor = Random().nextInt(Colors.primaries.length)
Colors.primaries[generatedColor]

example

import 'dart:math';

Icon(
    Icons.account_circle,
    size: 40,
    color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
)

Above is the simplest and fastest way to colorize your list with random colors. You don't need to maintain a list of colors.

Akbarsha
  • 2,422
  • 23
  • 34
37

You can use Random class to do that:

But if you want to change the color when button is pressed, you have to use a StatefulWidget. A simple example is like below:

import 'package:flutter/material.dart';
import 'dart:math';

void main() {
  runApp(
    MaterialApp(
      home: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  List colors = [Colors.red, Colors.green, Colors.yellow];
  Random random = new Random();

  int index = 0;

  void changeIndex() {
    setState(() => index = random.nextInt(3));
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () => changeIndex(),
        child: Text('Click'),
        color: colors[index],
      ),
    );
  }
}

Also, there is a package called random_pk by pawankumar, that will give us random color each and every time your app's build method get called.

Blasanka
  • 21,001
  • 12
  • 102
  • 104
22
import 'dart:math';
import 'dart:ui';

class Util {
  static Color randomColor() {
    return Color(Random().nextInt(0xffffffff));
  }
}

for opaque color:

static Color randomOpaqueColor() {
  return Color(Random().nextInt(0xffffffff)).withAlpha(0xff);
}
user3044484
  • 463
  • 5
  • 7
7

Another way to get tons of colors is using Random class with Color.fromARGB or Color.fromRGBO:

import 'dart:math';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyPage()));
}

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => new _MyPageState();
}

class _MyPageState extends State<MyPage> {
  final Random _random = Random();

  Color _color = Color(0xFFFFFFFF);

  void changeColor() {
    setState(() {
      _color = Color.fromARGB(
        //or with fromRGBO with fourth arg as _random.nextDouble(),
        _random.nextInt(256),
        _random.nextInt(256),
        _random.nextInt(256),
        _random.nextInt(256),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: InkWell(
        onTap: changeColor,
        child: Container(
          color: _color,
        ),
      ),
    );
  }
}

If you use Color.fromRGBO:

Fourth argument should be within 0.0 to 1.0 and fortunately we have _random.nextDouble() that gives a value between 0.0 to 1.0 randomly.

By the way:

  • R - Red
  • B - Blue
  • G - Green
  • O - Opacity
  • A - Alpha
Blasanka
  • 21,001
  • 12
  • 102
  • 104
7

To get random color I do the next:

import 'dart:math' as math;

final rnd = math.Random();

Color getRandomColor() => Color(rnd.nextInt(0xffffffff));
Andrew
  • 36,676
  • 11
  • 141
  • 113
5

This will generate a different color for the button everytime the build method for the app is called

    import 'package:flutter/material.dart';
    import 'dart:math';

    void main() => runApp(new MyApp());

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
      // TODO: implement build
        return new MaterialApp(
            title: "Raised Button",
            theme: new ThemeData(
               primarySwatch: Colors.teal,
            ),
            home: new HomePage());
      }
    }

    class HomePage extends StatefulWidget {
      @override
      HomePageState createState() => new HomePageState();
    }

    class HomePageState extends State<HomePage> {
      //contains the colours for the circle Avatars
      final List<Color> circleColors = [Colors.red, Colors.blue, Colors.green];

      Color randomGenerator() {
        return circleColors[new Random().nextInt(2)];
      }

      @override
      Widget build(BuildContext context) {
        return Center(
          child: RaisedButton(
            onPressed: () => {},
            child: Text('Click'),
            color: randomGenerator(),
          ),
        );
      }
  }
Kofi Nartey
  • 2,529
  • 2
  • 9
  • 5
5

In this way below you can obtain a random color with a one line command without needing any import:

 ([...Colors.primaries]..shuffle()).first

This is also a great example of cascade notation and spread operators in dart. Here you can find more information about it.

Jeison
  • 71
  • 1
  • 3
3

We can use random class for that But there is a random_color plugin in the flutter that can help us for generating random color and also we can select high saturation colors with this code:

import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor(
  colorSaturation: ColorSaturation.highSaturation
);

And light colors with this code:

import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor(
  colorBrightness: ColorBrightness.light
);

For more options read this https://pub.dev/packages/random_color#-readme-tab-

Arya
  • 547
  • 5
  • 5
2

I think we need a separate class for that (you can use static or top-level functions).

Just don't forget that nextInt: "Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive.". So set "max" to 0x100000000 (0xFFFFFFFF + 1)!

import 'dart:math';

import 'package:flutter/cupertino.dart';

class RandomColor {
  static const _MAX_VALUE = 0x100000000;
  final _random = Random();

  Color nextColor() => Color(_random.nextInt(_MAX_VALUE));
}
clevercat
  • 43
  • 1
  • 9
1

Well if you want distinguishable colors , this method gives 4096 different color with at least 16 level difference :

var rnd = Random();
var r = rnd.nextInt(16) * 16;
var g = rnd.nextInt(16) * 16;
var b = rnd.nextInt(16) * 16;
Color color = Color.fromARGB(255, r, g, b);
nullqube
  • 2,959
  • 19
  • 18
1

If we want to pick random colors from the Colors.primary class:

1- import:

import 'dart:math' as math show Random;

2- Set value:

final color = Colors.primaries[math.Random().nextInt(Colors.primaries.length)];

3- Use value:

backgroundColor: color,
smebes
  • 241
  • 3
  • 2
0

Simplest and best suggested way to do this is:

Step 1: Add dependency in pubspec.yaml random_color: ^1.0.3

Step 2: Add import import 'package:random_color/random_color.dart';

Step 3: In "color" attribute write color: RandomColor().randomColor();

Akshat Tamrakar
  • 2,193
  • 2
  • 13
  • 21
0

I do the easiest way,

import 'dart:math';

and then I use container as avatar

             Container(
                height: 100,
                width: 100,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(100),
                  color: Color.fromRGBO(
                    random.nextInt(255),
                    random.nextInt(255),
                    random.nextInt(255),
                    1,
                  ),
                ),
                child: const Icon(Icons.person, size: 60),
              )
Zia
  • 506
  • 3
  • 20
-1

Rounded Border with Random Color and Background

Try Using Package for Gmail Like effect. It will generate random color background. Also support selection widget

RoundedImageWithTextAndBG(
    radius: 20,
    isSelected: isSelected,
    uniqueId: textModel[widget.index]['uniqueId'],
    image: (widget.index % 3 == 0)
        ? 'https://picsum.photos/id/${widget.index}/800/800'
        : '',
    text: textModel[widget.index]['name'],
  ),
Juned Raza
  • 228
  • 3
  • 6