Simple library for generating random ascii strings

Overview

random_string

Simple library for generating random ascii strings.

Design goals and limitations

While this package provides randomBetween for convenience, as the name implies, the design goal of this package is for random generation of ascii strings, particularly for testing and not for cryptographic purposes.
With that stated, consider an alternative means of random number generation if your needs fall outside these goals and limitations.

Usage

A simple usage example:

import 'package:random_string/random_string.dart';
import 'dart:math' show Random;

main() {
  print(randomBetween(10, 20)); // some integer between 10 and 20 where 0 <= min <= max <= 999999999999999
  print(randomNumeric(4)); // sequence of 4 random numbers i.e. 3259
  print(randomString(10)); // random sequence of 10 characters i.e. e~f93(4l-
  print(randomAlpha(5)); // random sequence of 5 alpha characters i.e. aRztC
  print(randomAlphaNumeric(10)); // random sequence of 10 alpha numeric i.e. aRztC1y32B

  var r = Random.secure();
  print(randomBetween(10, 20, provider: CoreRandomProvider.from(r))); // You can use a provider from Random.
  print(randomBetween(10, 20, provider: _Provider())); // Or you can implement your own.
}

class _Provider with AbstractRandomProvider {
  _Provider();
  double nextDouble() => 0.5;
}

Features and bugs

Please file feature requests and bugs at the issue tracker.

Comments
  • Suggestion: Guaranteed full alpha-numeric character set?

    Suggestion: Guaranteed full alpha-numeric character set?

    The randomAlphaNumeric() function doesn't always return a full data set with a minimum of 1 of each possible characters. Basically I want to ensure we get at least 1 of each range: 0-9, a-z, and A-Z.

    In some cases I was getting only numbers, or only UPPER with numbers. I've worked around it with the below function, which I'm sure is probably the wrong way to do this, but it works for now.

    // Greg Fischer - guaranteed full data set of a-z A-Z and 0-9
    String randomAlphaNumericFullSet(int length){
    	String x = randomAlphaNumeric(length);
    	bool z = false;
    	while (z == false) {
    		//print('Assessing X: ${x}');
    		if(x.contains(new RegExp(r'[a-z]'))
    			&& x.contains(new RegExp(r'[A-Z]'))
    			&& x.contains(new RegExp(r'[0-9]'))
    		){
    			// print('contains a-z A-Z and 0-9 : ${x}');
    			z = true;
    		}
    		else {
    			x = randomAlphaNumeric(length);
    		}
    	}
    	return x;
    }
    
    enhancement acknowledged 
    opened by greg-fischer 8
  • random_string: ^2.0.1 package does not work

    random_string: ^2.0.1 package does not work

    I have -> added this package - random_string: ^2.0.1 in pubsec.yaml file -> pub.get ->import 'package:random_string/random_string.dart'; [this line gives error]

    I have attached the images --- randomString

    acknowledged 
    opened by SAMYAK99 7
  • alpha numeric  is not evenly distributed

    alpha numeric is not evenly distributed

    Because you first randomly choose how many characters are numeric and how many are alphanumeric, numerical characters are 4.8 (48/10) times as likely to occur then alphas. This reduces entropy, and thus increases collision probability (the total space of available strings stays the same).

    I would actually suggest to move away from the current ascii based approach as this is very easy to get wrong in some minor way and move to charsets as this seems far simpler and thus robust.

    this is my current internal implementation:

    const alphaNumericCharSet =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    String randomAlphaNumeric(int length) =>
        randomStringForCharset(length, alphaNumericCharSet);
    
    String randomStringForCharset(int length, String charset) {
      final random = Random();
      return [
        for (var i = 0; i < length; i++) charset[random.nextInt(charset.length)]
      ].join();
    }
    
    

    I could also create a merge request for this

    opened by felix-ht 3
  • Null-safety migration

    Null-safety migration

    Note that no code changes are necessary for null-safety. The only issue was related to the tests, but a minor small adjustment was able to negate any need to add a nullable type. So when the time comes to adopt null-safety, it is purely a compiler option.

    opened by awhitford 3
  • Package Version Update

    Package Version Update

    Updated the package version and changelog,

    0.0.2

    • Added Support for Dart 2
    • Fixed Error: The argument type 'dart.core::List'

    Also, would be nice if you could upload/update https://pub.dartlang.org/packages/random_string or add me as an uploader ([email protected])

    opened by riftninja 3
  • Error on current Dart

    Error on current Dart

    Not sure if you are maintaining this but I tried it in a test and got:

    compiler message: file:///Users/dking5/flutter/.pub-cache/hosted/pub.dartlang.org/random_string-0.0.1/lib/random_string.dart:76:35: Error: A value of type 'dart.core::List' can't be assigned to a variable of type 'dart.core::Iterabledart.core::int'. compiler message: Try changing the type of the left hand side, or casting the right hand side to 'dart.core::Iterabledart.core::int'. compiler message: return new String.fromCharCodes(mergedCodeUnits); compiler message: ^

    opened by dalewking 3
  • Conflict with Provider package

    Conflict with Provider package

    Hi. The Provider package is one of the most popular state management solutions available for Flutter, but we can't use it along with your package because there is a conflict, since you define the same name 'Provider'. In most cases it is not possible to stop using Provider, so we end up unistalling your package. Maybe change it so there are no conflicts in future versions?

    Error below:

    error: The name 'Provider' is defined in the libraries 'package:provider/src/provider.dart' and 'package:random_string/random_string.dart'. (ambiguous_import at [my_surgery] lib/screens/import_view.dart:124)

    Thanks.

    opened by lalo-vergel 2
  • randomBetween implementation is wrong

    randomBetween implementation is wrong

    The current implementation of randomBetween (as of 2.0.1) is:

    int randomBetween(int from, int to,
        {AbstractRandomProvider provider = const DefaultRandomProvider()}) {
      if (from > to) throw Exception('$from cannot be > $to');
      var randomDouble = provider.nextDouble();
      if (randomDouble < 0) randomDouble *= -1;
      if (randomDouble > 1) randomDouble = 1 / randomDouble;
      return ((to - from) * provider.nextDouble()).toInt() + from;
    }
    

    I see a few problems:

    • The documentation claims that the returned value should be in the range [from, to]. As implemented, however, if from != to, it can return values only in the range [from, to). The (to - from) factor should be (to - from + 1) to use an inclusive upper-bound. Consider a simple case of randomBetween(0, 1) where you want 2 possible values: Since toInt() truncates (rounds to 0), you ultimately want a double in the range [0, 2) so that toInt() can return an integer in the range [0, 1]. Assuming that provider.nextDouble() returns a fraction in the range [0, 1), you therefore must scale it by 2. Alternatively change the documented behavior. (The existing test to verify that randomBetween can return the inclusive upper-bound happens to work because it ends up being a degenerate case.)

    • randomBetween unnecessarily calls provider.nextDouble twice. It computes an adjusted randomDouble value but then proceeds to ignore it.

    • I see no documentation from AbstractRandomProvider specifying what nextDouble should return. Random.nextDouble from dart:math returns a value in the range [0, 1), but it's unclear what expectation AbstractRandomProvider has. This is a problem because:

    • That randomBetween tolerates provider.nextDouble() returning double values < 0 or > 1 suggests that any finite double values are legal. However, that could cause randomBetween to return random numbers without a uniform distribution, even if provider does have a uniform distribution. For example, suppose an AbstractRandomProvider is given whose nextDouble implementation returns a random double in the range [0, 100) with a uniform distribution, and suppose that we call randomBetween(0, 1, provider: myProvider). If randomDouble returns a value > 2 (which would happen 98% of the time), the > 1 check would adjust randomDouble to be < 0.5. Assuming that randomDouble were used in the final calculation instead of calling provider.nextDouble() again, this would give an undue weight to returning 0 instead of 1. I suggest:

      1. If provider.nextDouble returns a value outside the expected range, either fail or retry. Do not try to coerce it into the expected range because doing so is likely to change its distribution.
      2. Document that AbstractRandomProvider.nextDouble must return values in the range [0, 1).
    opened by jamesderlin 1
  •  Added support for SDK > 2.0

    Added support for SDK > 2.0

    What was the problem?

    Data type error could, also could not compile for sdk 2.0 and above

    How did I fix it?

    Changed List<dynamic> to List<int> for dart.core::Iterable<dart.core::int> Changed environment sdk to <3.0

    opened by riftninja 0
Releases(2.3.1)
Owner
Damon Douglas
go, dart, flutter, pizza, kombucha, cats: these are a few of my favorite things.
Damon Douglas
Dart library for unescaping HTML-encoded strings

html_unescape A Dart library for unescaping HTML-encoded strings. Supports: Named Character References ( ) 2099 of them Decimal Character Referen

Filip Hracek 36 Dec 20, 2022
A simple, unofficial AWS Polly client in dart. Supports generating a URL given an input text and voice identifier.

Flutter AWS Polly Plugin This plugin is a Flutter wrapper for AWS Polly which is a cloud service that converts text into lifelike speech. Getting Star

null 4 Aug 20, 2022
Dart Code Generator for generating mapper classes

Smartstruct - Dart bean mappings - the easy nullsafe way! Code generator for generating type-safe mappers in dart, inspired by https://mapstruct.org/

Nils 28 Nov 29, 2022
An alternative random library for Dart.

Randt Randt library for Dart... Description Use Randt to get a random integer from a list, generate random integer in a specific range and generate ra

Bangladesh Coding Soldierz 3 Nov 21, 2021
Flutter Cool Random User Generate 🔥🔥

Flutter Cool Random User Generate ????

Hmida 8 Sep 10, 2022
apps random

flutter_app A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if t

Tajul Aulia Muda 1 Oct 21, 2021
Random color generator for Flutter

Random color generator Pub link: https://pub.dartlang.org/packages/random_color This library will generate random colors that are visually pleasing an

Luka Knezic 56 Jun 13, 2022
Generate random data(string, integer, IPs etc...) using Dart.

Generate random data using Features API provides generation of: Integers in any range of numbers Strings with various characters and length Colors rep

Dinko Pehar 14 Apr 17, 2022
Minimal Dart wrapper to interact with Some Random Api. Easy to use, simplified and lightweight.

SRA - Some Random Api Minimal Dart wrapper to interact with Some Random Api. Easy to use, simplified and lightweight. Getting started Add the package

Yakiyo 3 Jan 4, 2023
Simple GEL converter to showcase Flutter basics. Fundamental widgets and simple methods.

gel_converter A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Tornike Gogberashvili 1 Oct 17, 2021
A simple command-line application to generate simple folder and file structure for Flutter Applications

Kanza_cli is a simple command line tool to generate folder and file structure for your Flutter apps. To use it, you should do the followings: 1. First

Kanan Yusubov 9 Dec 16, 2022
Args simple - A simple argument parser and handler, integrated with JSON and dart

args_simple A simple argument parser and handler, integrated with JSON and dart:

Graciliano Monteiro Passos 1 Jan 22, 2022
Fluro is a Flutter routing library that adds flexible routing options like wildcards, named parameters and clear route definitions.

Fluro is a Flutter routing library that adds flexible routing options like wildcards, named parameters and clear route definitions.

Luke Pighetti 3.5k Jan 4, 2023
A Dart library to parse Portable Executable (PE) format

pefile A Dart library to parse Portable Executable (PE) format Usage A simple usage example: var pe = pefile.parse('C:\\Windows\\System32\\notepad.exe

null 4 Sep 12, 2022
This library contains methods that make it easy to consume Mpesa Api.

This library contains methods that make it easy to consume Mpesa Api. It's multi-platform, and supports CLI, server, mobile, desktop, and the browser.

Eddie Genius 3 Dec 15, 2021
Scribble is a lightweight library for freehand drawing in Flutter supporting pressure, variable line width and more!

Scribble Scribble is a lightweight library for freehand drawing in Flutter supporting pressure, variable line width and more! A

Tim Created It. 73 Dec 16, 2022
A library for YAML manipulation with comment and whitespace preservation.

Yaml Editor A library for YAML manipulation while preserving comments. Usage A simple usage example: import 'package:yaml_edit/yaml_edit.dart'; void

Dart 17 Dec 26, 2022
The Dart Time Machine is a date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.

The Dart Time Machine is a date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.

null 2 Oct 8, 2021
A comprehensive, cross-platform path manipulation library for Dart.

A comprehensive, cross-platform path manipulation library for Dart. The path package provides common operations for manipulating paths: joining, split

Dart 159 Dec 29, 2022