randomAlphanumeric function

String randomAlphanumeric(
  1. int length, {
  2. bool isUppercase = false,
})

Returns a random alphanumeric string of length characters.

Draws from lowercase letters and digits by default; set isUppercase to use uppercase letters instead. A length of zero returns an empty string. Not cryptographically secure.

Example:

randomAlphanumeric(8); // e.g. 'a3f9k2qd'

Audited: 2026-06-12 11:26 EDT

Implementation

String randomAlphanumeric(int length, {bool isUppercase = false}) {
  // A non-positive length yields the empty string; without this guard a
  // negative length makes the list generator throw instead of degrading.
  if (length <= 0) return '';
  const String chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  final String pool = isUppercase ? chars.toUpperCase() : chars;
  return List<String>.generate(length, (_) => pool[_rnd.nextInt(pool.length)]).join();
}