Try it yourself with our free Uuid Generator tool — runs entirely in your browser, no signup needed.

How to Generate UUIDs in Dart

How to Generate UUIDs in Dart

Universally Unique Identifiers (UUIDs) are a crucial component in many applications, from data storage to networking. In Dart, generating UUIDs is a straightforward process, but it requires attention to detail to ensure correctness and efficiency. In this guide, we will explore the best practices for generating UUIDs in Dart, covering the most common use cases, edge cases, and performance tips.

Quick Example

Here is a minimal example of generating a UUID in Dart:

import 'package:uuid/uuid.dart';

void main() {
  var uuid = Uuid().v4();
  print(uuid);
}

To use this code, add the uuid package to your pubspec.yaml file:

dependencies:
  uuid: ^3.0.4

Then, run dart pub get to install the package.

Step-by-Step Breakdown

Let's walk through the code:

  • import 'package:uuid/uuid.dart';: We import the uuid package, which provides a simple and efficient way to generate UUIDs.
  • void main() { ... }: This is the entry point of our program.
  • var uuid = Uuid().v4();: We create a new instance of the Uuid class and call the v4() method to generate a random UUID.
  • print(uuid);: We print the generated UUID to the console.

Handling Edge Cases

Empty/Null Input

When working with user input, it's essential to handle empty or null values. In this case, we can use the Uuid class's v4() method, which generates a random UUID regardless of the input.

void main() {
  var input = null; // or ''
  var uuid = Uuid().v4();
  print(uuid);
}

Invalid Input

If the input is not a valid UUID, the Uuid class will throw an exception. We can catch this exception and handle it accordingly.

void main() {
  var input = ' invalid-uuid ';
  try {
    var uuid = Uuid().parse(input);
    print(uuid);
  } catch (e) {
    print('Invalid UUID: $e');
  }
}

Large Input

When working with large inputs, it's essential to ensure that the Uuid class can handle them efficiently. In this case, we can use the Uuid class's v4() method, which generates a random UUID regardless of the input size.

void main() {
  var input = 'a'.repeat(1000);
  var uuid = Uuid().v4();
  print(uuid);
}

Unicode/Special Characters

The Uuid class can handle Unicode and special characters without issues. However, it's essential to ensure that the input is correctly encoded.

void main() {
  var input = 'Hello, World!';
  var uuid = Uuid().v4();
  print(uuid);
}

Common Mistakes

1. Using the Wrong UUID Version

Using the wrong UUID version can lead to incorrect results. Make sure to use the correct version for your specific use case.

// Wrong
var uuid = Uuid().v1();

// Correct
var uuid = Uuid().v4();

2. Not Handling Exceptions

Not handling exceptions can lead to unexpected behavior. Make sure to catch and handle exceptions accordingly.

// Wrong
var uuid = Uuid().parse(' invalid-uuid ');

// Correct
try {
  var uuid = Uuid().parse(' invalid-uuid ');
} catch (e) {
  print('Invalid UUID: $e');
}

3. Not Validating Input

Not validating input can lead to incorrect results. Make sure to validate input before generating a UUID.

// Wrong
var input = ' invalid-uuid ';
var uuid = Uuid().parse(input);

// Correct
var input = ' invalid-uuid ';
if (input != null && input.isNotEmpty) {
  var uuid = Uuid().parse(input);
}

Performance Tips

1. Use the v4() Method

The v4() method is the most efficient way to generate a UUID in Dart. It uses a cryptographically secure pseudo-random number generator (CSPRNG) to generate a random UUID.

var uuid = Uuid().v4();

2. Avoid Generating UUIDs in Loops

Generating UUIDs in loops can be inefficient. Instead, generate a single UUID and reuse it.

// Wrong
for (var i = 0; i < 100; i++) {
  var uuid = Uuid().v4();
}

// Correct
var uuid = Uuid().v4();
for (var i = 0; i < 100; i++) {
  // Use the same UUID
}

3. Use the Uuid Class's parse() Method

The parse() method is more efficient than generating a new UUID.

// Wrong
var uuid = Uuid().v4();

// Correct
var uuid = Uuid().parse(' existing-uuid ');

FAQ

Q: What is the difference between UUID versions?

A: UUID versions determine the algorithm used to generate the UUID. Version 4 is the most commonly used and generates a random UUID.

Q: Can I use the Uuid class to generate a UUID from a string?

A: Yes, you can use the parse() method to generate a UUID from a string.

Q: How do I handle invalid UUIDs?

A: You can catch the exception thrown by the Uuid class and handle it accordingly.

Q: Can I generate UUIDs in parallel?

A: Yes, the Uuid class is thread-safe and can generate UUIDs in parallel.

Q: How do I validate UUIDs?

A: You can use the parse() method to validate UUIDs. If the input is invalid, the method will throw an exception.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp