Home > Software engineering >  How to randomise a-z letters in flutter/dart?
How to randomise a-z letters in flutter/dart?

Time:08-05

I want to do something like the

hello 1
hello 2
hello 3

but I want it to do this

fello
jello
aello
dello

Would I use dart:math to create a Random widget that produces a random integer and then somehow link it to the letters A-Z?

Thanks

CodePudding user response:

You can use the following function to genarate a string array with all the alphabetic letters. Refer About String.fromCharCode for more information.

//This function will return a string list with alphabet
List<String> getAlphebat() {
  List<String> alphabets = [];
  for (int i = 65; i <= 90; i  ) {
    alphabets.add(String.fromCharCode(i));
  }
  return alphabets;
}

And with the help of Random class in dart:math you can generate a random number. and access the particular index and get a random letter.

void main() {
  
  //Random Generator
  var randomGen = Random();
  
  //Generated random letter
  print(getAlphebat()[randomGen.nextInt(26)]);
  
}

String.fromCharCode

CodePudding user response:

import 'dart:math';

static getRandomString(length, [characterString]) {
  String _chars = characterString ?? 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
  Random _rnd = Random();
  return String.fromCharCodes(Iterable.generate(length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));
 }

Use below function to get random string, Here "character string" are optional to pass in function.

getRandomString(10, 'asABCCSSdsa');
  • Related