{

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


 Generate Random String in Dart and Flutter

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 the Iterable.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.

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.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.