How to: Generate Random String in Dart| Flutter By Example
Random Generator is used to generate a unique value for every invocation. This talks about multiple ways to generate a random string for example.
Dart/Flutter Random String generate example
This example generates a Random String with values.
Following are steps to follow.
- First, create a constant Character Array of alphabets and special characters.
- Find the Random number between zero to character array length
- Create a
List
of random Unicode numbers using theIterable.generate()
method - Generate a string from a List using the
String.fromCharCodes()
method
Here 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 Random Base64 encoded String generate example
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);
}
Conclusion
To summarize, Learn how to generate a Random String in dart with an example.