random_color 1.0.3

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new86

Random color generator

pub package

Pub link: https://pub.dartlang.org/packages/random_color

This library will generate random colors that are visually pleasing and can be customized by passing custom hue, saturation and brightness range. This allows it to generate just specific color with slight differences.

Blue colors:
Red colors:
Green:
Low saturation:
High saturation:
Light colors:
Dark colors:

Usage

Getting random color:

random color function can be called with parameters colorHue, colorSaturation and colorBrightness allowing for customization of colors the generator will pass.

import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor();
Getting color name:

You can get color name from hex string (without # and alpha hex values) or from Color object

  Color _color = Color('FF0000'.toStringRadix(16));
  MyColor _myColor = getColorNameFromColor(_color);

  // Prints: 'Red'
  print(_myColor.getName);
Get just red colors:

Random color can generate just specific color type, as long hue, saturation and brightness are not too limiting this will still give rich result

import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor(colorHue: ColorHue.red);
Get just red and blue colors:

You can combine multiple hue ranges to choose from

import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor(
  colorHue: ColorHue.multiple([ColorHue.red, ColorHue.blue])
);
Get highly saturated colors:
import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor(
  colorSaturation: ColorSaturation.highSaturation
);
Get light colors:
import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

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

Tests

If you want to run the tests for this project under Flutter Dart

flutter pub pub run test

[1.0.3] - 2018.10.20

  • Update example app
  • Set debug value default to false

[1.0.2] - 2018.10.20

  • Update description

[1.0.1] - 2018.10.17

  • Remove test dependency
  • Add description
  • Add randomColors function that returns lost of random colors
  • Change named parameter from ColorHue.custom() to required unnamed parameter
  • Change named parameter from ColorSaturation.custom() to required unnamed parameter
  • Change named parameter from ColorBrightness.custom() to required unnamed parameter

[1.0.0] - TODO: 2018.10.17

  • Initial release

example/lib/main.dart

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

void main() => runApp(MaterialApp(home: new MyApp()));

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

class _MyAppState extends State<MyApp> {
  List<Color> generatedColors = <Color>[];
  final List<ColorHue> _hueType = <ColorHue>[
    ColorHue.green,
    ColorHue.red,
    ColorHue.pink,
    ColorHue.purple,
    ColorHue.blue,
    ColorHue.yellow,
    ColorHue.orange
  ];
  ColorBrightness _colorLuminosity = ColorBrightness.random;
  ColorSaturation _colorSaturation = ColorSaturation.random;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('Example of Random colors library'),
      ),
      body: Container(child: _showColors()),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0),
            child: new FloatingActionButton(
              tooltip: 'RefreshColors',
              child: const Icon(Icons.refresh),
              onPressed: _updateColor,
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0),
            child: new FloatingActionButton(
              tooltip: 'Filter',
              child: const Icon(Icons.filter_list),
              onPressed: _showFilterDialog,
            ),
          ),
        ],
      ),
    );
  }

  Widget _showColors() {
    return GridView.builder(
      gridDelegate:
          const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        Color _color;

        if (generatedColors.length > index) {
          _color = generatedColors[index];
        } else {
          _color = RandomColor().randomColor(
              colorHue: ColorHue.multiple(colorHues: _hueType),
              colorSaturation: _colorSaturation,
              colorBrightness: _colorLuminosity);

          generatedColors.add(_color);
        }

        Color getTextColor() {
          if (_color == null) {
            return Colors.black;
          }

          if (_color.computeLuminance() > 0.3) {
            return Colors.black;
          } else {
            return Colors.white;
          }
        }

        return Card(
          color: _color,
          child: Container(
            margin: const EdgeInsets.all(12.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    getColorNameFromColor(_color).getName,
                    style: Theme.of(context)
                        .textTheme
                        .title
                        .copyWith(fontSize: 13.0, color: getTextColor()),
                  ),
                ),
                Container(
                  alignment: Alignment.centerRight,
                  child: Text(
                    '#${_color.value.toRadixString(16).toUpperCase()}',
                    style: Theme.of(context).textTheme.caption.copyWith(
                        color: getTextColor(),
                        fontSize: 16.0,
                        fontWeight: FontWeight.w300),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showFilterDialog() async {
    await showDialog<Null>(
        context: context,
        builder: (BuildContext context) {
          return FilterDialog(
            hueType: _hueType,
            colorLuminosity: _colorLuminosity,
            colorSaturation: _colorSaturation,
            hueTypeChange: (List<ColorHue> hues) {
              _hueType.clear();
              _hueType.addAll(hues);
            },
            luminosityTypeChange: (ColorBrightness cb) => _colorLuminosity = cb,
            saturationTypeChange: (ColorSaturation cs) => _colorSaturation = cs,
          );
        }).catchError(print);

    _updateColor();
  }

  void _updateColor() {
    setState(() {
      generatedColors.clear();
    });
  }
}

typedef void HueTypeChange(List<ColorHue> colorHues);
typedef void SaturationTypeChange(ColorSaturation colorSaturation);
typedef void LuminosityTypeChange(ColorBrightness colorBrightness);

class FilterDialog extends StatefulWidget {
  FilterDialog({
    Key key,
    this.hueType,
    this.colorSaturation,
    this.colorLuminosity,
    this.hueTypeChange,
    this.saturationTypeChange,
    this.luminosityTypeChange,
  }) : super(key: key);

  final List<ColorHue> hueType;
  final ColorBrightness colorLuminosity;
  final ColorSaturation colorSaturation;

  final HueTypeChange hueTypeChange;
  final SaturationTypeChange saturationTypeChange;
  final LuminosityTypeChange luminosityTypeChange;

  @override
  _FilterDialogState createState() => new _FilterDialogState();
}

class _FilterDialogState extends State<FilterDialog> {
  final List<ColorHue> _hueType = <ColorHue>[];
  ColorBrightness _colorLuminosity;
  ColorSaturation _colorSaturation;

  @override
  void initState() {
    super.initState();

    _hueType.addAll(widget.hueType);
    _colorLuminosity = widget.colorLuminosity;
    _colorSaturation = widget.colorSaturation;
  }

  @override
  Widget build(BuildContext context) {
    return SimpleDialog(children: <Widget>[
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              color: Colors.white,
              child: Text('Color hue: '),
            ),
            Container(
              height: 175.0,
              width: MediaQuery.of(context).size.width * 0.5,
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: ColorHue.values.length,
                itemBuilder: (BuildContext context, int index) {
                  final ColorHue _hue = _hueType.firstWhere(
                      (ColorHue hue) => hue.type == ColorHue.values[index].type,
                      orElse: () => null);
                  final Color _color = RandomColor(8).randomColor(
                      colorHue: ColorHue.values[index],
                      colorSaturation: _colorSaturation,
                      colorBrightness: _colorLuminosity);

                  return Container(
                    height: 50.0,
                    child: Flex(
                      direction: Axis.horizontal,
                      children: <Widget>[
                        Container(
                          height: 50.0,
                          width: 12.0,
                          color: _color,
                        ),
                        Expanded(
                          child: Container(
                            color: _color.withOpacity(0.1),
                            padding: const EdgeInsets.all(8.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(ColorHue.values[index].toString()),
                                Checkbox(
                                  value: _hue != null,
                                  onChanged: (bool value) {
                                    if (_hue != null) {
                                      _removeColorHue(_hue);
                                    } else {
                                      _addColorHue(ColorHue.values[index]);
                                    }

                                    _hueType.removeWhere(
                                        (ColorHue hue) => hue == null);
                                    widget.hueTypeChange(_hueType);
                                  },
                                )
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              color: Colors.white,
              child: Text('Color brightness: '),
            ),
            DropdownButton<int>(
              value: _colorLuminosity.type,
              onChanged: (int luminosity) {
                setState(() =>
                    _colorLuminosity = ColorBrightness.values[luminosity]);

                widget.luminosityTypeChange(_colorLuminosity);
              },
              items: ColorBrightness.values
                  .map((ColorBrightness l) => DropdownMenuItem<int>(
                      child: Container(child: Text(l.toString())),
                      value: l.type))
                  .toList(),
            )
          ],
        ),
      ),
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              color: Colors.white,
              child: Text('Color saturation: '),
            ),
            DropdownButton<int>(
              value: _colorSaturation.type,
              onChanged: (int saturation) {
                setState(() =>
                    _colorSaturation = ColorSaturation.values[saturation]);

                widget.saturationTypeChange(_colorSaturation);
              },
              items: ColorSaturation.values
                  .map((ColorSaturation cf) => DropdownMenuItem<int>(
                      child: Container(child: Text(cf.toString())),
                      value: cf.type))
                  .toList(),
            )
          ],
        ),
      ),
    ]);
  }

  void _addColorHue(ColorHue c) {
    setState(() {
      _hueType.add(c);
    });
  }

  void _removeColorHue(ColorHue c) {
    setState(() {
      _hueType.remove(c);

      if (_hueType.isEmpty) {
        _hueType.add(ColorHue.random);
      }
    });
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  random_color: ^1.0.3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:random_color/random_color.dart';
  
Version Uploaded Documentation Archive
1.0.3 Oct 22, 2018 Go to the documentation of random_color 1.0.3 Download random_color 1.0.3 archive
1.0.2 Oct 20, 2018 Go to the documentation of random_color 1.0.2 Download random_color 1.0.2 archive
1.0.1 Oct 20, 2018 Go to the documentation of random_color 1.0.1 Download random_color 1.0.1 archive
1.0.0 Oct 17, 2018 Go to the documentation of random_color 1.0.0 Download random_color 1.0.0 archive
0.0.1 Oct 17, 2018 Go to the documentation of random_color 0.0.1 Download random_color 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
73
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
86
Learn more about scoring.

We analyzed this package on Nov 14, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.6
  • Flutter: 0.11.3

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test