rnd 0.1.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 83

rnd package #

Makes working with random values in Dart / Flutter easier:

  1. It provides an easy to access, global instance of Random.
  2. It adds helpful extension methods to Random.

Global instance #

To make it easy to set up and propagate a Random instance throughout your app, the rnd package exposes a global instance via the rnd property. This makes generating a random value as simple as:

import 'package:rnd/rnd.dart';
rnd(10); // random double between 0-10
rnd.getBool(0.8); // 80% chance to get true

You can also get and set the seed for the global instance via rndSeed.

Extension methods on Random #

Adds the following methods to all instances of Random. Read the docs for more info.

  • getInt(min, max, {curve}) // see "Curves" below
  • getDouble(min, max, {curve})
  • getBool(chance)
  • getBit(chance) // 0 or 1
  • getSign(chance) // -1 or 1
  • getDeg() // 0-360
  • getRad() // 0-2pi
  • getColor({...}) // see docs for params
  • getItem(list, {remove, curve})
  • shuffle(list, {copy}) // randomize list

It also defines a call method, which lets you get a random double value by calling a Random instance directly:

Random myRandom = new Random();
print(myRandom()); // double between 0-1
print(myRandom(10)); // 0-10
print(myRandom(5,10)); // 5-10

This pairs well with the global instance for quickly getting random values:

new Point(rnd(maxX), rnd(maxY))

Curves #

The getDouble, getInt, and getItem methods support a curve param which transforms the value distribution. For example:

rnd.getInt(0, 100, curve: Curves.easeIn)

This would favor values nearer to 0, whereas easeOut would favor values nearer to 100. The included example app visualizes the effect of different curves.

Hue #

The included Hue class provides named hue values for use with getColor. For example, Hue.green == 120.

rnd.getColor(hue: Hue.red); // red, green, blue, yellow, cyan, magenta

[0.1.0] - 2019-05-10 #

Added #

  • First release.

example/lib/main.dart

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Curve Test',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Curve Distribution Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String selectedCurve = 'linear (or none)';

  @override
  Widget build(BuildContext context) {
    _runTests();

    List<DropdownMenuItem<String>> curves = [];
    curveMap.forEach((k, v) {
      curves.add(DropdownMenuItem<String>(value: k, child: Text(k), ));
    });

    Curve curve = curveMap[selectedCurve];
    List<FractionalOffset> points = [];
    
    for (int i=0; i<25000; i++) {
      points.add(FractionalOffset(
        rnd.getDouble(0, 1, curve: curve),
        rnd.getDouble(0, 1),
      ));
    }

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(widget.title, style: TextStyle(color: Colors.black),),
        backgroundColor: Colors.white,
      ),
      body: Column(mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.stretch, children:[
        Container(
          color: Colors.white,
          child: Row(mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            _ValueLabel("0 →"),
            DropdownButton(
              value: selectedCurve,
              onChanged: (item) => setState(() { selectedCurve = item; }),
              items: curves,
            ),
            _ValueLabel("← 1"),
          ],),
        ),
        Expanded(child: CustomPaint(
          painter: _PointPainter(points: points),
          child: Container(),
        )),
      ]),
    );
  }

  Widget _ValueLabel(String label) {
    return Padding(
      padding: EdgeInsets.all(12.0),
      child: Text(label, style: TextStyle(fontWeight: FontWeight.bold)),
    );
  }
}

void _runTests() {
  // TODO: these should get moved to proper tests and/or visualized.
  _runTest("rnd()", ()=>rnd());
  _runTest("rnd(10)", ()=>rnd(10));
  _runTest("rnd(10, 20)", ()=>rnd(10, 20));
  print("rndSeed: $rndSeed");

  print("\n");
  _runTest("int, 40-50, easeOut", ()=>rnd.getInt(40, 50, curve:Curves.easeOutQuint));
  _runTest("double, 40-50, easeOut", ()=>rnd.getDouble(40, 50, curve:Curves.easeOutQuint).toStringAsFixed(2));
  _runTest("bool, 0.75", ()=>rnd.getBool(0.75));
  _runTest("bit, 0.75", ()=>rnd.getBit(0.75));
  _runTest("sign, 0.75", ()=>rnd.getSign(0.75));
  _runTest("deg", ()=>rnd.getDeg());
  _runTest("rad", ()=>rnd.getRad());

  print("\n");
  _runTest("color", ()=>rnd.getColor());
  _runTest("red", ()=>rnd.getColor(hue: Hue.red, hueRange: 20, minSaturation: 0.5, lightness: 0.5));
  _runTest("magenta->yellow", ()=>rnd.getColor(minHue: Hue.magenta, maxHue: Hue.yellow, saturation: 1.0, lightness: 0.5));
  _runTest("alpha > 0.5", ()=>rnd.getColor(minAlpha: 0.5, lightness: 0.0));

  List list = ["zero", "one", "two", "three", "four"];
  List shuffled = rnd.shuffle(list, copy: true);

  print("\n");
  print('list: $list');
  print('shuffled: $shuffled');

  _runTest("item, false", ()=>rnd.getItem(list), 2);
  print('list: $list');

  _runTest("item, true", ()=>rnd.getItem(list, remove:true), 2);
  print('list: $list');
}

_runTest(String label, Function f, [int count=10]) {
  String str = '$label: [';
  for (int i=0; i<count; i++) { str += '${f()}, '; }
  print('$str]');
}

class _PointPainter extends CustomPainter {
  List<FractionalOffset> points;

  _PointPainter({@required this.points});

  @override
  void paint(Canvas canvas, Size size) {
    if (points == null || points.length == 0) { return; }
    Paint dot = new Paint()..color = Colors.blue.withOpacity(0.5);
    dot.blendMode = BlendMode.screen;
    int l = points.length;
    for (int i=0; i < l; i++) {
      canvas.drawCircle(points[i].alongSize(size), 1.7, dot);
    }
  }

  @override
  bool shouldRepaint(_PointPainter oldPainter) {
    return true;
  }

}

// Curves that return values outside 0-1 are commented out.
const Map<String, Curve> curveMap = {
  'bounceIn': Curves.bounceIn,
  'bounceInOut': Curves.bounceInOut,
  'bounceOut': Curves.bounceOut,
  'decelerate': Curves.decelerate,
  'ease': Curves.ease,
  'easeIn': Curves.easeIn,
//'easeInBack': Curves.easeInBack,
  'easeInCirc': Curves.easeInCirc,
  'easeInCubic': Curves.easeInCubic,
  'easeInExpo': Curves.easeInExpo,
  'easeInOut': Curves.easeInOut,
//'easeInOutBack': Curves.easeInOutBack,
  'easeInOutCirc': Curves.easeInOutCirc,
  'easeInOutCubic': Curves.easeInOutCubic,
  'easeInOutExpo': Curves.easeInOutExpo,
  'easeInOutQuad': Curves.easeInOutQuad,
  'easeInOutQuart': Curves.easeInOutQuart,
  'easeInOutQuint': Curves.easeInOutQuint,
  'easeInOutSine': Curves.easeInOutSine,
  'easeInQuad': Curves.easeInQuad,
  'easeInQuart': Curves.easeInQuart,
  'easeInQuint': Curves.easeInQuint,
  'easeInSine': Curves.easeInSine,
  'easeInToLinear': Curves.easeInToLinear,
  'easeOut': Curves.easeOut,
//'easeOutBack': Curves.easeOutBack,
  'easeOutCirc': Curves.easeOutCirc,
  'easeOutCubic': Curves.easeOutCubic,
  'easeOutExpo': Curves.easeOutExpo,
  'easeOutQuad': Curves.easeOutQuad,
  'easeOutQuart': Curves.easeOutQuart,
  'easeOutQuint': Curves.easeOutQuint,
  'easeOutSine': Curves.easeOutSine,
//'elasticIn': Curves.elasticIn,
//'elasticInOut': Curves.elasticInOut,
//'elasticOut': Curves.elasticOut,
  'fastLinearToSlowEaseIn': Curves.fastLinearToSlowEaseIn,
  'fastOutSlowIn': Curves.fastOutSlowIn,
  'linear (or none)': Curves.linear,
  'linearToEaseOut': Curves.linearToEaseOut,
  'slowMiddle': Curves.slowMiddle,
};

Use this package as a library

1. Depend on it

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


dependencies:
  rnd: ^0.1.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

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

3. Import it

Now in your Dart code, you can use:


import 'package:rnd/rnd.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
65
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]
83
Learn more about scoring.

We analyzed this package on Jul 10, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • rnd that is a package requiring null.

Health suggestions

Format lib/rnd.dart.

Run flutter format to format lib/rnd.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8 1.2.2
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
flutter_test