Skip to main content
Dart

How to Generate UUID in Dart/Flutter

Using the uuid package

Dart's standard library has no built-in UUID generator — for that you'll want the uuid package from pub.dev, which turns a couple of lines of code into a random, RFC 4122-compliant UUID string ready for database keys, API payloads, or Flutter widget identifiers. Add the package once, then call Uuid().v4() whenever you need a fresh identifier, or reach for its timestamp-based and name-based variants when random won't do. Below you'll find copy-paste ready code for generating a Dart UUID, validating a string against the UUID format, and the alternate generation methods the same package ships with. The python uuid reference shows how to use uuid.uuid4() as a Django model default without extra dependencies.

Generate UUID in Dart

var uuid = Uuid(); uuid.v4()
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in Dart

Dart's core SDK has no built-in UUID generator, so the standard approach is the uuid package from pub.dev — add it to pubspec.yaml, then call Uuid().v4() for a random, RFC 4122-compliant identifier. See the go uuid page for UUID primary keys in GORM and pgx with optimal PostgreSQL storage.

pubspec.yaml
dependencies:
  uuid: ^4.0.0  # check pub.dev for the latest version
main.dart
import 'package:uuid/uuid.dart';

final uuid = Uuid();

void main() {
  final myUuid = uuid.v4();
  print(myUuid);
  // Output: 550e8400-e29b-41d4-a716-446655440000
}

Explanation

Convert a String to a UUID in Dart

Dart's uuid package treats UUIDs as plain strings — there's no dedicated UUID class to parse into, so "converting" really means validating that a string matches the UUID format before you trust it, using the package's Uuid.isValidUUID() static helper. The scala uuid reference explains how to use UUID.randomUUID() in idiomatic Scala with type safety.

main.dart
import 'package:uuid/uuid.dart';

void main() {
  const input = '550e8400-e29b-41d4-a716-446655440000';

  if (Uuid.isValidUUID(fromString: input)) {
    print('Valid UUID: $input');
  } else {
    print('Invalid UUID format');
  }
}

Explanation

Other Options for Generating UUIDs in Dart

The same uuid package that generates v4 identifiers also covers timestamp-based and deterministic UUIDs, so there's no extra dependency to add when your use case calls for something other than random.

main.dart
import 'package:uuid/uuid.dart';

final uuid = Uuid();

void main() {
  // Version 1 - timestamp + node ID, sortable by creation time
  final uuidV1 = uuid.v1();

  // Version 5 - deterministic, same namespace + name always produce the same UUID
  final uuidV5 = uuid.v5(Uuid.NAMESPACE_URL, 'https://example.com');
}

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!