How to: Generate Random String in Dart| Flutter By Example

Random Generator is utilized to produce a unique value for each invocation. This post elaborates on various methods for generating a random string, providing examples for each.

Dart/Flutter Example: Generating a Random String

This example demonstrates the generation of a random string with specified length.

Here are the steps to follow:

  • First, create a constant character array containing alphabets and special characters.
  • Then, generate a random number within the range of the character array’s length.
  • Create a List of random Unicode numbers using the Iterable.generate() method.
  • Finally, generate a string from the list using the String.fromCharCodes() method.

Below is the example 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 Example: Generating a Random Base64 Encoded String

dart:convert library provides conversion utilities such as the base64UrlEncode class. By using Random.secure(), cryptographically secure random numbers are generated from the platform’s OS. The process involves creating a list of integers through the generate method and then converting the list into an encoded byte 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

In conclusion, this post has provided examples on how to generate random strings in Dart, showcasing different methods and libraries.