{

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 the Iterable.generate() method
  • Generate a string from a List using 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 number from 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.





Related posts

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example