In this tutorial, we’ll learn how to properly generate Dart random string by using practical Dart code example.
Introduction: Dart Random String
It specifies the process through which a string of random characters will be returned. We’ll also allow the code to return a specific length of Dart random string.
Implementing Dart Random String (Easy Example Code)
We’ll now implement a function which will generate and return a random string of alphabets and numbers everytime its called. See below steps:
Step 1: import dart:math
import 'dart:math'; // in order to use random function
Step 2: Define the Function which will Generate Random String
String generateRandomString(int lengthOfString){ final random = Random(); const allChars='AaBbCcDdlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1EeFfGgHhIiJjKkL234567890'; // below statement will generate a random string of length using the characters // and length provided to it final randomString = List.generate(lengthOfString, (index) => allChars[random.nextInt(allChars.length)]).join(); return randomString; // return the generated string }
Step 3: Called this Function
print(generateRandomString(10)); print(generateRandomString(5)); print(generateRandomString(15)); String randomStringReturned= generateRandomString(6); // can store the returned value in string variable print(randomStringReturned);
Output
sZAPvahLG8 NTneR Xy8tkxBIbNBDSkd GMScOT
So by using this function, we can easily generate a Dart random string of any specific length.