Home > Net >  How can I generate random string with a fixed length of number or special characters in Flutter?
How can I generate random string with a fixed length of number or special characters in Flutter?

Time:11-05

I am trying to generate a string or password. where the user defines minimum numbers or special characters. if the minimum number is 3 then generated string should have 3 numbers

here is the code i used to generate string

String generaterandomPassword() {
        final length = _length.toInt();
        const letterLowerCase = "abcdefghijklmnopqrstuvwxyz";
        const letterUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const number = '0123456789';
        const special = '@#%^*>\$@?/[]= ';
    
        String chars = "";
        // if (letter) chars  = '$letterLowerCase$letterUpperCase';
        if (_uppercaseatoz) chars  = letterUpperCase;
        if (_lowercaseatoz) chars  = letterLowerCase;
        if (_number) chars  = number;
        if (_specialchar) chars  = special;
    
        return List.generate(
          length,
          (index) {
            final indexRandom = Random.secure().nextInt(chars.length);
            return chars[indexRandom];
          },
        ).join('');
      }

CodePudding user response:

Tbh I would just use a flutter package rather than build it yourself. Let's you focus on the important stuff. Try https://pub.dev/documentation/basic_utils/latest/basic_utils/StringUtils-class.html

generateRandomString method.

CodePudding user response:

One way to guarantee a minimum number of "special" characters is:

  1. Generate a string with that minimum length that consists of only special characters.
  2. Randomly choose any characters for the remainder.
  3. Shuffle all of the generated characters.

For example:

import 'dart:math';

final random = Random.secure();

const letterLowerCase = "abcdefghijklmnopqrstuvwxyz";
const letterUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const number = '0123456789';
const special = '@#%^*>\$@?/[]= ';

String generatePassword({
  required int length,
  required int minimumSpecialCharacterCount,
}) {
  assert(length >= minimumSpecialCharacterCount);
  
  const allValidCharacters = '$letterLowerCase$letterUpperCase$number$special';

  var specials = [
    for (var i = 0; i < minimumSpecialCharacterCount; i  = 1)
      special[random.nextInt(special.length)],
  ];

  var rest = [
    for (var i = 0; i < length - minimumSpecialCharacterCount; i  = 1)
      allValidCharacters[random.nextInt(allValidCharacters.length)],
  ];

  return ((specials   rest)..shuffle(random)).join();
}

void main() {
  print(generatePassword(length: 16, minimumSpecialCharacterCount: 3));
}
  • Related