Flutter how to generate random strings
1,745
Solution 1
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?
Solution 2
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))));```
Author by
sebi
Updated on December 19, 2022Comments
-
sebi over 1 year
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); }
-
Christopher Moore about 3 yearsDoes this answer your question? How to generate random string in dart?
-
-
iDecode about 3 yearsInstead of coping the answer, you could have flagged the post as duplicate.