Skip to content

Generate UUID in Dart

Dart doesn't have built-in UUID support, but you can use the popular uuid package. Here's how to generate a random UUID version 4:

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

void main() {
  var uuid = Uuid();
  
  // Generate UUID version 4 - random
  String uuidV4 = uuid.v4();
  print('Generated UUID: $uuidV4');
}

For generating specific UUID versions, the uuid package provides comprehensive support:

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

void main() {
  var uuid = Uuid();

  // Generate UUID version 1 - time based
  String uuidV1 = uuid.v1();
  print('UUID v1: $uuidV1');

  // Generate UUID version 3 - deterministic and hashed with MD5
  String uuidV3 = uuid.v3(Uuid.NAMESPACE_URL, 'https://example.com');
  print('UUID v3: $uuidV3');

  // Generate UUID version 4 - random
  String uuidV4 = uuid.v4();
  print('UUID v4: $uuidV4');

  // Generate UUID version 5 - deterministic and hashed with SHA-1
  String uuidV5 = uuid.v5(Uuid.NAMESPACE_URL, 'https://example.com');
  print('UUID v5: $uuidV5');

  // Generate UUID version 6 - time-ordered (if supported)
  try {
    String uuidV6 = uuid.v6();
    print('UUID v6: $uuidV6');
  } catch (e) {
    print('UUID v6 not supported in this version');
  }

  // Generate UUID version 7 - time-ordered with random (if supported)
  try {
    String uuidV7 = uuid.v7();
    print('UUID v7: $uuidV7');
  } catch (e) {
    print('UUID v7 not supported in this version');
  }
}

Installation & Setup

Add to pubspec.yaml:

yaml
dependencies:
  uuid: ^4.2.1

Install the package:

bash
dart pub get
# or for Flutter projects
flutter pub get

Flutter Integration

Basic Flutter App with UUID Generation:

dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uuid/uuid.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'UUID Generator',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: UUIDGeneratorPage(),
    );
  }
}

class UUIDGeneratorPage extends StatefulWidget {
  @override
  _UUIDGeneratorPageState createState() => _UUIDGeneratorPageState();
}

class _UUIDGeneratorPageState extends State<UUIDGeneratorPage> {
  final Uuid _uuid = Uuid();
  String _currentUUID = '';
  String _selectedVersion = 'v4';

  void _generateUUID() {
    setState(() {
      switch (_selectedVersion) {
        case 'v1':
          _currentUUID = _uuid.v1();
          break;
        case 'v3':
          _currentUUID = _uuid.v3(Uuid.NAMESPACE_URL, 'example.com');
          break;
        case 'v4':
          _currentUUID = _uuid.v4();
          break;
        case 'v5':
          _currentUUID = _uuid.v5(Uuid.NAMESPACE_URL, 'example.com');
          break;
        default:
          _currentUUID = _uuid.v4();
      }
    });
  }

  void _copyToClipboard() {
    Clipboard.setData(ClipboardData(text: _currentUUID));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('UUID copied to clipboard!')),
    );
  }

  @override
  void initState() {
    super.initState();
    _generateUUID();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('UUID Generator')),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            DropdownButton<String>(
              value: _selectedVersion,
              onChanged: (String? newValue) {
                setState(() {
                  _selectedVersion = newValue!;
                });
                _generateUUID();
              },
              items: ['v1', 'v3', 'v4', 'v5']
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text('UUID $value'),
                );
              }).toList(),
            ),
            SizedBox(height: 20),
            Container(
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(8),
              ),
              child: SelectableText(
                _currentUUID,
                style: TextStyle(
                  fontFamily: 'monospace',
                  fontSize: 16,
                ),
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _generateUUID,
              child: Text('Generate New UUID'),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: _copyToClipboard,
              child: Text('Copy to Clipboard'),
            ),
          ],
        ),
      ),
    );
  }
}

UUID Service Class:

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

class UUIDService {
  static final Uuid _uuid = Uuid();

  // Generate different UUID versions
  static String generateV1() => _uuid.v1();
  static String generateV3(String name, [String? namespace]) => 
      _uuid.v3(namespace ?? Uuid.NAMESPACE_URL, name);
  static String generateV4() => _uuid.v4();
  static String generateV5(String name, [String? namespace]) => 
      _uuid.v5(namespace ?? Uuid.NAMESPACE_URL, name);

  // Validate UUID format
  static bool isValidUUID(String uuid) {
    final uuidRegex = RegExp(
      r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
    );
    return uuidRegex.hasMatch(uuid);
  }

  // Parse UUID and get version
  static int? getUUIDVersion(String uuid) {
    if (!isValidUUID(uuid)) return null;
    
    final versionChar = uuid[14];
    return int.tryParse(versionChar);
  }

  // Generate UUID with custom options
  static String generateCustom({
    UUIDVersion version = UUIDVersion.v4,
    String? name,
    String? namespace,
  }) {
    switch (version) {
      case UUIDVersion.v1:
        return generateV1();
      case UUIDVersion.v3:
        return generateV3(name ?? 'default', namespace);
      case UUIDVersion.v4:
        return generateV4();
      case UUIDVersion.v5:
        return generateV5(name ?? 'default', namespace);
    }
  }
}

enum UUIDVersion { v1, v3, v4, v5 }

Advanced Dart Usage

UUID Model Class:

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

class UUIDModel {
  final String id;
  final DateTime createdAt;
  final int version;

  UUIDModel._({
    required this.id,
    required this.createdAt,
    required this.version,
  });

  factory UUIDModel.generate({UUIDVersion version = UUIDVersion.v4}) {
    final uuid = Uuid();
    String id;
    
    switch (version) {
      case UUIDVersion.v1:
        id = uuid.v1();
        break;
      case UUIDVersion.v3:
        id = uuid.v3(Uuid.NAMESPACE_URL, DateTime.now().toString());
        break;
      case UUIDVersion.v4:
        id = uuid.v4();
        break;
      case UUIDVersion.v5:
        id = uuid.v5(Uuid.NAMESPACE_URL, DateTime.now().toString());
        break;
    }

    return UUIDModel._(
      id: id,
      createdAt: DateTime.now(),
      version: version.index + 1,
    );
  }

  factory UUIDModel.fromString(String uuidString) {
    if (!UUIDService.isValidUUID(uuidString)) {
      throw ArgumentError('Invalid UUID format');
    }

    return UUIDModel._(
      id: uuidString,
      createdAt: DateTime.now(),
      version: UUIDService.getUUIDVersion(uuidString) ?? 4,
    );
  }

  Map<String, dynamic> toJson() => {
    'id': id,
    'createdAt': createdAt.toIso8601String(),
    'version': version,
  };

  factory UUIDModel.fromJson(Map<String, dynamic> json) => UUIDModel._(
    id: json['id'],
    createdAt: DateTime.parse(json['createdAt']),
    version: json['version'],
  );

  @override
  String toString() => id;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is UUIDModel && runtimeType == other.runtimeType && id == other.id;

  @override
  int get hashCode => id.hashCode;
}

Database Integration (SQLite):

dart
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:uuid/uuid.dart';

class DatabaseHelper {
  static final DatabaseHelper _instance = DatabaseHelper._internal();
  static Database? _database;
  final Uuid _uuid = Uuid();

  factory DatabaseHelper() => _instance;
  DatabaseHelper._internal();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    String path = join(await getDatabasesPath(), 'app_database.db');
    return await openDatabase(
      path,
      version: 1,
      onCreate: _onCreate,
    );
  }

  Future<void> _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE users (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        email TEXT NOT NULL,
        created_at TEXT NOT NULL
      )
    ''');
  }

  Future<String> insertUser(String name, String email) async {
    final db = await database;
    final id = _uuid.v4();
    
    await db.insert('users', {
      'id': id,
      'name': name,
      'email': email,
      'created_at': DateTime.now().toIso8601String(),
    });
    
    return id;
  }

  Future<Map<String, dynamic>?> getUser(String id) async {
    final db = await database;
    final results = await db.query(
      'users',
      where: 'id = ?',
      whereArgs: [id],
    );
    
    return results.isNotEmpty ? results.first : null;
  }
}

Testing UUID Generation

Unit Tests:

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

void main() {
  group('UUID Generation Tests', () {
    final uuid = Uuid();

    test('should generate valid UUID v4', () {
      final uuidV4 = uuid.v4();
      expect(UUIDService.isValidUUID(uuidV4), isTrue);
      expect(UUIDService.getUUIDVersion(uuidV4), equals(4));
    });

    test('should generate deterministic UUID v5', () {
      final uuid1 = uuid.v5(Uuid.NAMESPACE_URL, 'test');
      final uuid2 = uuid.v5(Uuid.NAMESPACE_URL, 'test');
      expect(uuid1, equals(uuid2));
    });

    test('should generate unique UUID v4', () {
      final uuid1 = uuid.v4();
      final uuid2 = uuid.v4();
      expect(uuid1, isNot(equals(uuid2)));
    });

    test('should validate UUID format', () {
      final validUUID = uuid.v4();
      const invalidUUID = 'invalid-uuid';
      
      expect(UUIDService.isValidUUID(validUUID), isTrue);
      expect(UUIDService.isValidUUID(invalidUUID), isFalse);
    });
  });
}

UUID Version Comparison

Choose the right version for your Dart/Flutter application:

  • Version 1 - Time-based, includes MAC address
  • Version 3 - MD5 namespace-based, deterministic
  • Version 4 - Random, most popular choice
  • Version 5 - SHA-1 namespace-based, more secure than v3
  • Version 6 - Time-ordered, better than v1 for databases
  • Version 7 - Modern time-based with improved sorting

For Dart/Flutter applications:

  • Mobile apps: Use Version 4 for local data and user sessions
  • Real-time features: Consider Version 7 for chat messages and events
  • Offline sync: Use Version 1 for device-specific identification

How do I generate UUID in other languages?

Mobile development:

  • Swift - iOS native development
  • Kotlin - Android native development
  • Java - Android development

Web and backend:

← Back to Online UUID Generator