During development, there are times when we may need to generate random numbers, alphabets, characters with a specified length. In this article, I will walk you through how to generate random string using that ‘dart:math‘ library.
The idea will be to allow user to choose options as to how they want the random string to be generated. That is, they may want to specify the length of the string, choose if it should include uppercase or lowercase letters, or to include special characters.
This library is Mathematical constants and functions, plus a random number generator. We will be using the Random class of the library which provide us the methods to generate random bool, int, or double values.
However, we are not generating random int, bool or doubles in our own case, so we have to find a way to make sure we able to generate string+number+specialxters.
Random String Generator Class
Let’s start by creating the class that will generate the random string. Create a class named RandomStringGenerator, and instantiate the Random class in the constructor, this requires that we import ‘dart:math’ library like so:
Now let’s add the uppercase,lowercase,numbers and symbols for our use, modify the class like so:
Random String Generator Method
We will add a method that will generate the random string and return the result string based on the option chosen. Let’s add a method named nextString that is similar to the Random class nextInt method. This method will take some arguments that will allow user to choose how they want the random string to be generated like so:
With the way the method parameters are named, they are all self explanatory, hence we don’t have to explain one by one.
The login to generate the random string is here below, I will explain how it works later.
The method logic is straightforward, we created a list of string with the specified length, then check the value of the parameters and based on that we append the strings.
The we loop through the specified length and use the Random.nextInt to get a random number betwen 0 and the specified length and the add the character in that index into our empty list and then finally return the string using List.join method.
Using the Class
To use the class is very simple just create an instance of the class then call the nextString method and pass the arguments. like so:
var randomStr = RandomStringGenerator();
var randomNo = randomStr.NextString(20,true,true,true,false);
The Complete Code
The full code look like this:
I hope this helps. If you know a better way this can be done please don’t hesitate to let me know.