Dart

How to Generate UUID in Dart/Flutter

Using the uuid package

Use the code examples below to generate UUIDs in Dart and Flutter using the uuid package — create version 1, v4, and v5 unique identifiers with just a few lines of code. Copy these Dart UUID snippets into your Flutter mobile apps, web applications, or server-side Dart projects for unique ID generation in local databases, API requests, state management, and anywhere your cross-platform application needs globally unique identifiers.

Generate UUID in Dart

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

Installation

Add the uuid package to your pubspec.yaml:

pubspec.yaml
dependencies:
  uuid: ^4.3.3

# Or run in terminal:
# dart pub add uuid
# flutter pub add uuid

Note: Run flutter pub get or dart pub get after adding the dependency.

Generate UUID v4 (Random)

The most common use case - generating random UUIDs:

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

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

  // UUID v4 (random) - most common
  String v4 = uuid.v4();
  print(v4);  // 550e8400-e29b-41d4-a716-446655440000
  
  // Generate multiple
  for (int i = 0; i < 5; i++) {
    print(uuid.v4());
  }
  
  // Use with options
  var options = {
    'random': Uuid.NAMESPACE_NIL  // Custom random source
  };
  String customV4 = uuid.v4(options: options);
}

All UUID Versions

Generate different UUID versions for various use cases:

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

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

  // UUID v1 (timestamp + MAC address)
  String v1 = uuid.v1();
  print('v1: $v1');
  
  // UUID v4 (random) - most common
  String v4 = uuid.v4();
  print('v4: $v4');
  
  // UUID v5 (SHA-1 hash based)
  String v5 = uuid.v5(Uuid.NAMESPACE_URL, 'https://example.com');
  print('v5: $v5');
  
  // UUID v6 (timestamp, ordered)
  String v6 = uuid.v6();
  print('v6: $v6');
  
  // UUID v7 (Unix timestamp, sortable)
  String v7 = uuid.v7();
  print('v7: $v7');
  
  // UUID v8 (custom format)
  String v8 = uuid.v8();
  print('v8: $v8');
}

Validation

Validate UUID format and check versions:

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

bool isValidUuid(String str) {
  return Uuid.isValidUUID(fromString: str);
}

void main() {
  // Validate UUID
  print(isValidUuid('550e8400-e29b-41d4-a716-446655440000'));  // true
  print(isValidUuid('not-a-uuid'));  // false
  
  // Check with validation levels
  print(Uuid.isValidUUID(
    fromString: '550e8400-e29b-41d4-a716-446655440000',
    validationMode: ValidationMode.strictRFC4122
  ));
  
  // Parse and validate
  String input = '550e8400-e29b-41d4-a716-446655440000';
  if (Uuid.isValidUUID(fromString: input)) {
    print('Valid UUID: $input');
  } else {
    print('Invalid UUID format');
  }
}

Flutter Model with UUID

Use UUIDs as primary keys in Flutter models:

Dart - Flutter Model
import 'package:uuid/uuid.dart';

class TodoItem {
  final String id;
  final String title;
  final String description;
  bool isComplete;
  final DateTime createdAt;

  TodoItem({
    String? id,
    required this.title,
    this.description = '',
    this.isComplete = false,
    DateTime? createdAt,
  })  : id = id ?? const Uuid().v4(),
        createdAt = createdAt ?? DateTime.now();

  // To JSON
  Map toJson() => {
        'id': id,
        'title': title,
        'description': description,
        'isComplete': isComplete,
        'createdAt': createdAt.toIso8601String(),
      };

  // From JSON
  factory TodoItem.fromJson(Map json) => TodoItem(
        id: json['id'],
        title: json['title'],
        description: json['description'] ?? '',
        isComplete: json['isComplete'] ?? false,
        createdAt: DateTime.parse(json['createdAt']),
      );

  // Copy with
  TodoItem copyWith({
    String? id,
    String? title,
    String? description,
    bool? isComplete,
    DateTime? createdAt,
  }) =>
      TodoItem(
        id: id ?? this.id,
        title: title ?? this.title,
        description: description ?? this.description,
        isComplete: isComplete ?? this.isComplete,
        createdAt: createdAt ?? this.createdAt,
      );
}

// Usage
void main() {
  var todo = TodoItem(title: 'Learn Dart UUID');
  print('Todo ID: ${todo.id}');
}

Flutter State Management with UUID

Integrate UUIDs with Provider state management:

Flutter - Provider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';

class TodoProvider extends ChangeNotifier {
  final List _todos = [];
  final uuid = Uuid();

  List get todos => _todos;

  void addTodo(String title) {
    final todo = TodoItem(
      id: uuid.v4(),
      title: title,
    );
    _todos.add(todo);
    notifyListeners();
  }

  void toggleTodo(String id) {
    final index = _todos.indexWhere((t) => t.id == id);
    if (index != -1) {
      _todos[index] = _todos[index].copyWith(
        isComplete: !_todos[index].isComplete,
      );
      notifyListeners();
    }
  }

  void deleteTodo(String id) {
    _todos.removeWhere((t) => t.id == id);
    notifyListeners();
  }
}

// Flutter Widget
class TodoListView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, provider, child) {
        return ListView.builder(
          itemCount: provider.todos.length,
          itemBuilder: (context, index) {
            final todo = provider.todos[index];
            return ListTile(
              key: Key(todo.id),  // Use UUID as key
              title: Text(todo.title),
              trailing: Checkbox(
                value: todo.isComplete,
                onChanged: (_) => provider.toggleTodo(todo.id),
              ),
            );
          },
        );
      },
    );
  }
}

SQLite Database Integration

Use UUIDs with sqflite for local storage:

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

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;
  final uuid = Uuid();

  DatabaseHelper._init();

  Future get database async {
    if (_database != null) return _database!;
    _database = await _initDB('todos.db');
    return _database!;
  }

  Future _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(
      path,
      version: 1,
      onCreate: _createDB,
    );
  }

  Future _createDB(Database db, int version) async {
    await db.execute('''
      CREATE TABLE todos (
        id TEXT PRIMARY KEY,
        title TEXT NOT NULL,
        description TEXT,
        is_complete INTEGER NOT NULL,
        created_at TEXT NOT NULL
      )
    ''');
  }

  Future create(TodoItem todo) async {
    final db = await instance.database;
    
    final id = uuid.v4();
    final todoWithId = todo.copyWith(id: id);
    
    await db.insert('todos', todoWithId.toJson());
    return todoWithId;
  }

  Future readTodo(String id) async {
    final db = await instance.database;
    
    final maps = await db.query(
      'todos',
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return TodoItem.fromJson(maps.first);
    }
    return null;
  }

  Future> readAllTodos() async {
    final db = await instance.database;
    final result = await db.query('todos');
    return result.map((json) => TodoItem.fromJson(json)).toList();
  }

  Future delete(String id) async {
    final db = await instance.database;
    return await db.delete(
      'todos',
      where: 'id = ?',
      whereArgs: [id],
    );
  }
}

Firebase Integration

Use UUIDs with Cloud Firestore:

Flutter - Firestore
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:uuid/uuid.dart';

class FirestoreTodoService {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  final uuid = Uuid();

  Future createTodo(String title) async {
    final id = uuid.v4();
    final todo = TodoItem(
      id: id,
      title: title,
    );

    await _firestore
        .collection('todos')
        .doc(id)
        .set(todo.toJson());

    return todo;
  }

  Future getTodo(String id) async {
    final doc = await _firestore
        .collection('todos')
        .doc(id)
        .get();

    if (doc.exists) {
      return TodoItem.fromJson(doc.data()!);
    }
    return null;
  }

  Stream> getTodosStream() {
    return _firestore
        .collection('todos')
        .orderBy('createdAt', descending: true)
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map((doc) => TodoItem.fromJson(doc.data()))
            .toList());
  }

  Future updateTodo(String id, Map updates) async {
    await _firestore
        .collection('todos')
        .doc(id)
        .update(updates);
  }

  Future deleteTodo(String id) async {
    await _firestore
        .collection('todos')
        .doc(id)
        .delete();
  }
}

Riverpod State Management

Modern state management with Riverpod:

Flutter - Riverpod
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:uuid/uuid.dart';

final uuidProvider = Provider((ref) => Uuid());

class TodoNotifier extends StateNotifier> {
  TodoNotifier(this.uuid) : super([]);
  
  final Uuid uuid;

  void addTodo(String title) {
    final todo = TodoItem(
      id: uuid.v4(),
      title: title,
    );
    state = [...state, todo];
  }

  void toggleTodo(String id) {
    state = [
      for (final todo in state)
        if (todo.id == id)
          todo.copyWith(isComplete: !todo.isComplete)
        else
          todo,
    ];
  }

  void removeTodo(String id) {
    state = state.where((todo) => todo.id != id).toList();
  }
}

final todoProvider = StateNotifierProvider>((ref) {
  final uuid = ref.watch(uuidProvider);
  return TodoNotifier(uuid);
});

// Usage in Widget
class TodoScreen extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final todos = ref.watch(todoProvider);
    
    return ListView.builder(
      itemCount: todos.length,
      itemBuilder: (context, index) {
        final todo = todos[index];
        return ListTile(
          key: ValueKey(todo.id),
          title: Text(todo.title),
          trailing: IconButton(
            icon: Icon(Icons.delete),
            onPressed: () {
              ref.read(todoProvider.notifier).removeTodo(todo.id);
            },
          ),
        );
      },
    );
  }
}

Other Programming Language UUID Guides

Comments & Feedback

Share your experience or ask questions about this tool

Copied!