Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random string in dart?

Tags:

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?

like image 830
G19TV Avatar asked May 20 '20 17:05

G19TV


People also ask

How do you get a random string in darts?

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.

How do you generate random names on flutter?

please try this code: import "dart:math"; List names = ['jerry','mark','john']; // generates a new Random object final _random = new Random(); // generate a random index based on the list length // and use it to retrieve the element var element = names[_random. nextInt(names. length)];


2 Answers

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.

like image 182
julemand101 Avatar answered Sep 24 '22 04:09

julemand101


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(); } 
like image 26
kontinuity Avatar answered Sep 22 '22 04:09

kontinuity