generateUUIDv4 static method

String generateUUIDv4()

Generates a version 4 (random) UUID (Universally Unique Identifier).

This method generates a random UUIDv4 following the RFC 4122 standard. UUIDs generated by this method are suitable for unique identifiers in various applications. UUIDv4s are 128-bit long and typically represented as a hexadecimal string separated by hyphens.

Returns: A random UUIDv4 as a string in the format "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".

Example:

final uuid = generateUUIDv4();
print(uuid); /// Output: "550e8400-e29b-41d4-a716-446655440000"

Implementation

static String generateUUIDv4() {
  final random = math.Random.secure();

  /// Generate random bytes for the UUIDv4.
  final bytes = List<int>.generate(16, (i) {
    if (i == 6) {
      return (random.nextInt(16) & 0x0f) | 0x40;
    } else if (i == 8) {
      return (random.nextInt(4) & 0x03) | 0x08;
    } else {
      return random.nextInt(256);
    }
  });

  /// Set the 6th high-order bit of the 6th byte to indicate version 4.
  bytes[6] = (bytes[6] & 0x0f) | 0x40;

  /// Set the 7th high-order bit of the 8th byte to indicate variant RFC4122.
  bytes[8] = (bytes[8] & 0x3f) | 0x80;

  /// Convert bytes to a hexadecimal string with hyphen-separated groups.
  final List<String> hexBytes =
      bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).toList();

  return '${hexBytes.sublist(0, 4).join('')}-${hexBytes.sublist(4, 6).join('')}-'
      '${hexBytes.sublist(6, 8).join('')}-${hexBytes.sublist(8, 10).join('')}-'
      '${hexBytes.sublist(10).join('')}';
}