Uuid.fromString constructor

Uuid.fromString(
  1. String uuidString
)

Creates a UUID from a string representation.

Parameters:

  • uuidString: String representation of the UUID

Accepts standard UUID format with hyphens (8-4-4-4-12) or without hyphens. Parsing is case-insensitive but output is always lowercase.

Supported Formats

  • 550e8400-e29b-41d4-a716-446655440000 (standard format)
  • 550e8400e29b41d4a716446655440000 (compact format)
  • Mixed case variations

Example

final uuid1 = Uuid.fromString('550e8400-e29b-41d4-a716-446655440000');
final uuid2 = Uuid.fromString('550E8400E29B41D4A716446655440000');
print(uuid1 == uuid2); // true

Throws:

Implementation

factory Uuid.fromString(String uuidString) {
  if (uuidString.isEmpty) {
    throw InvalidFormatException('UUID string cannot be empty');
  }

  // Remove hyphens and convert to lowercase
  final cleanString = uuidString.replaceAll('-', '').toLowerCase();

  if (cleanString.length != 32) {
    throw InvalidFormatException('Invalid UUID string length: ${uuidString.length}');
  }

  // Validate hex characters
  if (!RegExp(r'^[0-9a-f]{32}$').hasMatch(cleanString)) {
    throw InvalidFormatException('Invalid UUID string format: $uuidString');
  }

  try {
    final mostSigBits = BigInt.parse(cleanString.substring(0, 16), radix: 16);
    final leastSigBits = BigInt.parse(cleanString.substring(16, 32), radix: 16);
    return Uuid._(BigInteger.fromBigInt(mostSigBits), BigInteger.fromBigInt(leastSigBits));
  } catch (e) {
    throw InvalidFormatException('Failed to parse UUID string: $uuidString\n $e');
  }
}