G19TV
G19TV

Reputation: 1085

How to generate random string in dart?

I want to create a function that generates a random string in dart. It should include alphabets and numbers all mixed together. How can I do that?

Upvotes: 96

Views: 89358

Answers (8)

Sanjay Bharwani
Sanjay Bharwani

Reputation: 4829

Things have changed over the years, now we don't need any of extra code to generate random strings and credit goes to StringUtils from basic_utils package.

Add entry in pubspec.yaml

basic_utils: ^5.7.0

Now use generateRandomString method.

Below are few examples

StringUtils.generateRandomString(3, special: false), //3 alphanumeric characters
StringUtils.generateRandomString(35) // this includes special chars
StringUtils.generateRandomString(35, special: false, numeric: false), //only alphabets
StringUtils.generateRandomString(35, special: false, alphabet: false), //only number

So, just pass the required parameter from the below parameters list and it will generate a random string for you.

static String generateRandomString(
    int length, {
    alphabet = true,
    numeric = true,
    special = true,
    uppercase = true,
    lowercase = true,
    String from = '',
  })

Upvotes: 0

Jamirul islam
Jamirul islam

Reputation: 866

import 'dart:math';

String generateRandomPassword(int length) {
  const String charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_+';

  Random random = Random();
  String password = '';

  for (int i = 0; i < length; i++) {
    int randomIndex = random.nextInt(charset.length);
    password += charset[randomIndex];
  }

  return password;
}

void main() {
  int passwordLength = 12; // Change this to your desired password length
  String password = generateRandomPassword(passwordLength);
  print('Random Password: $password');
}

Upvotes: 1

parsa sahab
parsa sahab

Reputation: 1

import 'dart:math';
String randomPassword(int length){
    String characters =
      'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
  Random rndInt = Random();
  String password = '';
  for (int i = 0; i <lenght; i++){
    password +=characters[rndInt.nextInt(characters.length)];
  }
  return ('Your new password is $password');

}

Upvotes: 0

Arash
Arash

Reputation: 944

If you care about the uniqueness and security of your random string, you can use UUID package easily

var uuid = Uuid();
// Generate a v1 (time-based) id
uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
// Generate a v4 (random) id
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

Upvotes: 4

sohrabonline
sohrabonline

Reputation: 664

import 'dart:math';
    
    String generateRandomString(int len) {
    var r = Random();
    String randomString =String.fromCharCodes(List.generate(len, (index)=> r.nextInt(33) + 89));
      return randomString;
    }

Upvotes: 10

julemand101
julemand101

Reputation: 31299

Or if you don't want to use a package you can make a simple implementation like:

import 'dart:math';

void main() {
  print(getRandomString(5));  // 5GKjb
  print(getRandomString(10)); // LZrJOTBNGA
  print(getRandomString(15)); // PqokAO1BQBHyJVK
}

const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
Random _rnd = Random();

String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
    length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));

I should add that you should not use this code to generate passwords or other kind of secrets. If you do that, please at least use Random.secure() to create the random generator.

Upvotes: 203

jnnks
jnnks

Reputation: 896

Found this in a blog article about crypto strings:

import 'dart:math';
import 'dart:convert';

String getRandString(int len) {
  var random = Random.secure();
  var values = List<int>.generate(len, (i) =>  random.nextInt(255));
  return base64UrlEncode(values);
}

The string always ends with ==. I would also assume that it's not the fastest solution. But you don't need third party packages and don't have to declare obscure constants.

Upvotes: 26

Arif Amirani
Arif Amirani

Reputation: 26705

Option A with charCodes:

import 'dart:math';

String generateRandomString(int len) {
  var r = Random();
  return String.fromCharCodes(List.generate(len, (index) => r.nextInt(33) + 89));
}

Generates random string using visible characters including special ones.

Option B with a predefined string:

import 'dart:math';

String generateRandomString(int len) {
  var r = Random();
  const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
  return List.generate(len, (index) => _chars[r.nextInt(_chars.length)]).join();
}

Upvotes: 42

Related Questions