Reputation: 35
Hello does anyone know how I can only generate Strings with letters. Like :
"skdnjfsd" or "bdfvkjnd" ?
my current code :
String _randomString(int length) {
var rand = new Random();
var codeUnits = new List.generate(
length,
(index){
return rand.nextInt(33)+89;
}
);
return new String.fromCharCodes(codeUnits);
}
Upvotes: 3
Views: 5320
Reputation: 404
implement to your code this function
String getRandom(int length){
const ch = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
Random r = Random();
return String.fromCharCodes(Iterable.generate(
length, (_) => ch.codeUnitAt(r.nextInt(ch.length))));
}
and after call it with length
the original answer : How to generate random string in dart?
Upvotes: 3
Reputation: 272
As per the answer of @julemand101, you can do this:
import 'dart:math';
void main() {
print(getRandomString(5)); // 5GKjb
print(getRandomString(10)); // LZrJOTBNGA
print(getRandomString(15)); // PqokAO1BQBHyJVK
}
const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
Random _rnd = Random();
String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));```
Upvotes: 2