nextString method
Generate the next random string of specific length
.
If no parameter is provided, it will return a random string using ASCII characters only (character code 0 to 127).
If whitelist
or blacklist
are provided, they will get priority over
other parameters. Otherwise, these two list will be generated from the
other parameter.
Other Parameters:
lower
: lowercase letters.upper
: uppercase letters.controls
: control characters.punctuations
: punctuations.
If these parameters are set, it will be ignored. Otherwise, if true
, the
corresponding characters will be added to the whitelist
, or if false
,
to the blacklist
.
If the whitelist
is already set, these parameters has no effect when
they are set to true. If the blacklist
is already set, these parameters
has no effect when they are set to false.
Implementation
String nextString(
int length, {
bool? lower,
bool? upper,
bool? numeric,
bool? controls,
bool? punctuations,
List<int>? whitelist,
List<int>? blacklist,
}) {
Set<int> white = {};
Set<int> black = {};
if (lower != null) {
if (lower) {
white.addAll(_alphaLower.codeUnits);
} else {
black.addAll(_alphaLower.codeUnits);
}
}
if (upper != null) {
if (upper) {
white.addAll(_alphaUpper.codeUnits);
} else {
black.addAll(_alphaUpper.codeUnits);
}
}
if (numeric != null) {
if (numeric) {
white.addAll(_numeric.codeUnits);
} else {
black.addAll(_numeric.codeUnits);
}
}
if (controls != null) {
if (controls) {
white.addAll(_controls);
} else {
black.addAll(_controls);
}
}
if (punctuations != null) {
if (punctuations) {
white.addAll(_punctuations);
} else {
black.addAll(_punctuations);
}
}
if (whitelist != null) {
white.addAll(whitelist);
black.removeAll(whitelist);
} else if (white.isEmpty) {
white.addAll(List.generate(128, (i) => i));
}
white.removeAll(black);
if (blacklist != null) {
white.removeAll(blacklist);
}
if (white.isEmpty) {
throw StateError('Empty whitelist');
}
var list = white.toList(growable: false);
Iterable<int> codes = nextBytes(length);
codes = codes.map((x) => list[x % list.length]);
return String.fromCharCodes(codes);
}