THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
Random Generator is used to generate a unique value for every invocation. This talks about multiple ways to generate a random string for example.
This example generates a Random String with values.
Following are steps to follow.
List
of random Unicode numbers using the Iterable.generate()
methodString.fromCharCodes()
methodHere is an example program code
import 'dart:math';
void main() async {
print(getRandomString(10)); //ynAIrUMKfk
print(getRandomString(10)); //YEgY-EI?Ss
print(getRandomString(10)); //CxjjeIIRAn
}
String getRandomString(int length) {
const characters =
'+-*=?AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
Random random = Random();
return String.fromCharCodes(Iterable.generate(
length, (_) => characters.codeUnitAt(random.nextInt(characters.length))));
}
dart:convert
provides conversion utilities such as base64UrlEncode
class.
Random.secure()
generates cryptographically secure random numbers from the platform OS.
Create a List of integers using the generate
method
Convert the list into encoded bytes string using base64UrlEncode
.
Here is an example program.
import 'dart:math';
import 'dart:convert';
void main() async {
print(getBase64RandomString(20)); //NEteMh73f6VtQMbypjdyCh69nLM=
print(getBase64RandomString(20)); //nsrv3EJf8sqt6C4bsAeO0T-ro-A=
}
String getBase64RandomString(int length) {
var random = Random.secure();
var values = List<int>.generate(length, (i) => random.nextInt(255));
return base64UrlEncode(values);
}
To summarize, Learn how to generate a Random String in dart with an example.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts