Flutter apps frequently need stable identifiers for local SQLite records, offline sync queues, analytics events, and navigation arguments — all before any network connection. UUID v7 generated on the device carries a millisecond creation timestamp, so records from multiple devices merge in chronological order on the server. The uuid Dart package is the standard library for UUID generation in Flutter and Dart.

Installing the uuid Package

# pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  uuid: ^4.0.0
flutter pub get

The uuid package has no native platform dependencies — it works on iOS, Android, Web, macOS, Windows, and Linux without any additional configuration.

Generating UUIDs

import 'package:uuid/uuid.dart';

const uuid = Uuid();

// UUID v4 — cryptographically random, 122 bits of entropy
final v4 = uuid.v4();
print(v4); // 550e8400-e29b-41d4-a716-446655440000

// UUID v7 — time-ordered, index-friendly
final v7 = uuid.v7();
print(v7); // 018fbe3a-4c5d-7000-8abc-0123456789ab

const Uuid() is a lightweight object — create one instance and reuse it. The package uses dart:math’s Random.secure() for cryptographic-quality randomness, which reads from the OS entropy source on all supported platforms.

Typed UUID Wrappers

Dart’s type system allows domain-specific ID types that prevent accidentally passing the wrong UUID to a function:

import 'package:uuid/uuid.dart';

const _uuid = Uuid();

extension type UserId(String value) {
  factory UserId.generate() => UserId(_uuid.v7());
  factory UserId.parse(String s) {
    if (!Uuid.isValidUUID(fromString: s)) {
      throw FormatException('Invalid UserId: $s');
    }
    return UserId(s);
  }
}

extension type OrderId(String value) {
  factory OrderId.generate() => OrderId(_uuid.v7());
}

// Compiler error if UserId and OrderId are swapped
void processOrder(UserId userId, OrderId orderId) { /* ... */ }

Dart 3 extension types have zero runtime overhead — the underlying value is still a String at runtime.

sqflite — UUID v7 Primary Keys

The sqflite package provides SQLite access on iOS and Android. Store UUIDs as TEXT:

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

const _uuid = Uuid();

class TaskDatabase {
  static Database? _db;

  static Future<Database> get database async {
    _db ??= await openDatabase(
      join(await getDatabasesPath(), 'tasks.db'),
      onCreate: (db, version) => db.execute('''
        CREATE TABLE tasks (
          id        TEXT NOT NULL PRIMARY KEY,
          title     TEXT NOT NULL,
          completed INTEGER NOT NULL DEFAULT 0,
          synced    INTEGER NOT NULL DEFAULT 0
        )
      '''),
      version: 1,
    );
    return _db!;
  }

  static Future<String> createTask(String title) async {
    final db = await database;
    final id = _uuid.v7(); // UUID v7 — encodes creation time
    await db.insert('tasks', {'id': id, 'title': title});
    return id;
  }

  // ORDER BY id = chronological order (UUID v7 lexicographic = time order)
  static Future<List<Map<String, dynamic>>> listTasks({
    String? cursor,
    int limit = 20,
  }) async {
    final db = await database;
    if (cursor != null) {
      return db.query(
        'tasks',
        where: 'id > ?',
        whereArgs: [cursor],
        orderBy: 'id',
        limit: limit,
      );
    }
    return db.query('tasks', orderBy: 'id', limit: limit);
  }

  static Future<void> updateTask(String id, {bool? completed}) async {
    final db = await database;
    await db.update(
      'tasks',
      {'completed': completed == true ? 1 : 0},
      where: 'id = ?',
      whereArgs: [id],
    );
  }
}

drift (Type-Safe SQLite ORM)

drift (formerly Moor) is a type-safe SQLite ORM for Flutter. Define UUID columns as TextColumn:

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

const _uuid = Uuid();

class Tasks extends Table {
  TextColumn get id => text().clientDefault(() => _uuid.v7())();
  TextColumn get title => text()();
  BoolColumn get completed => boolean().withDefault(const Constant(false))();
  DateTimeColumn get createdAt => dateTime().clientDefault(DateTime.now)();

  @override
  Set<Column> get primaryKey => {id};
}

// Usage in a DAO
@DriftAccessor(tables: [Tasks])
class TaskDao extends DatabaseAccessor<AppDatabase> with _$TaskDaoMixin {
  TaskDao(super.db);

  Future<String> createTask(String title) async {
    final id = _uuid.v7();
    await into(tasks).insert(TasksCompanion.insert(
      id: id,
      title: title,
    ));
    return id;
  }

  Stream<List<Task>> watchAllTasks() =>
      (select(tasks)..orderBy([(t) => OrderingTerm.asc(t.id)])).watch();
}

clientDefault generates a UUID v7 automatically on each insert, matching the pattern of database-level DEFAULT gen_random_uuid() in PostgreSQL.

Offline-First Sync Queue

UUID v7 makes offline sync straightforward — the timestamp in the UUID encodes when the user performed the action, so replaying actions in the correct order requires only sorting by ID:

import 'package:sqflite/sqflite.dart';
import 'package:uuid/uuid.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

const _uuid = Uuid();

enum SyncOperation { create, update, delete }

class SyncQueue {
  final Database _db;
  SyncQueue(this._db);

  Future<void> init() => _db.execute('''
    CREATE TABLE IF NOT EXISTS sync_queue (
      id         TEXT NOT NULL PRIMARY KEY,
      operation  TEXT NOT NULL,
      table_name TEXT NOT NULL,
      payload    TEXT NOT NULL,
      synced     INTEGER NOT NULL DEFAULT 0
    )
  ''');

  /// Enqueue an operation while offline.
  /// UUID v7 id encodes when the user performed the action.
  Future<String> enqueue(
    SyncOperation op,
    String table,
    Map<String, dynamic> payload,
  ) async {
    final id = _uuid.v7();
    await _db.insert('sync_queue', {
      'id': id,
      'operation': op.name,
      'table_name': table,
      'payload': jsonEncode(payload),
    });
    return id;
  }

  /// Flush — ORDER BY id replays actions in original user order (UUID v7 = time-ordered)
  Future<void> flush(String serverUrl) async {
    final pending = await _db.query(
      'sync_queue',
      where: 'synced = 0',
      orderBy: 'id', // UUID v7 lexicographic order = chronological
    );

    for (final record in pending) {
      final response = await http.post(
        Uri.parse('$serverUrl/sync'),
        headers: {'Content-Type': 'application/json'},
        body: record['payload'] as String,
      );

      if (response.statusCode == 200 || response.statusCode == 409) {
        // 409 = already processed (idempotent) — mark as synced
        await _db.update(
          'sync_queue',
          {'synced': 1},
          where: 'id = ?',
          whereArgs: [record['id']],
        );
      }
    }
  }
}

Hive — UUID Keys in NoSQL Local Storage

Hive CE (community edition of Hive) is a fast key-value store for Flutter. Use UUID v7 strings as box keys:

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

const _uuid = Uuid();

@HiveType(typeId: 0)
class Note extends HiveObject {
  @HiveField(0)
  final String id; // UUID v7 — stored as key and field for query flexibility

  @HiveField(1)
  final String content;

  Note({required this.id, required this.content});
}

class NoteRepository {
  final Box<Note> _box;
  NoteRepository(this._box);

  String create(String content) {
    final id = _uuid.v7();
    _box.put(id, Note(id: id, content: content));
    return id;
  }

  Note? get(String id) => _box.get(id);

  /// Returns notes in creation order — Hive keys are sorted as strings,
  /// UUID v7 lexicographic sort = chronological.
  List<Note> listAll() {
    final keys = _box.keys.cast<String>().toList()..sort();
    return keys.map((k) => _box.get(k)!).toList();
  }
}

UUID in Flutter Navigation and State

UUID v7 is useful as a route argument for navigating to a specific record, and as a state identifier in complex forms:

// Passing a UUID as a navigation argument
Navigator.pushNamed(
  context,
  '/task-detail',
  arguments: taskId, // UUID v7 string
);

// Receiving it in the destination widget
class TaskDetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final taskId = ModalRoute.of(context)!.settings.arguments as String;
    return FutureBuilder(
      future: TaskDatabase.getTask(taskId),
      builder: (context, snapshot) {
        // ...
      },
    );
  }
}

// Stable list item keys prevent unnecessary rebuilds
ListView.builder(
  itemCount: tasks.length,
  itemBuilder: (context, index) {
    return TaskTile(
      key: ValueKey(tasks[index].id), // UUID v7 key — stable across re-sorts
      task: tasks[index],
    );
  },
)

Validation and Parsing

import 'package:uuid/uuid.dart';

bool isValidUuid(String value) =>
    Uuid.isValidUUID(fromString: value);

// Version-specific validation
bool isUuidV7(String value) {
  if (!isValidUuid(value)) return false;
  // Version nibble is the 13th character (index 14)
  return value[14] == '7';
}

// Extract creation timestamp from UUID v7
DateTime uuidV7ToDateTime(String id) {
  final hex = id.replaceAll('-', '').substring(0, 12);
  final ms = int.parse(hex, radix: 16);
  return DateTime.fromMillisecondsSinceEpoch(ms);
}

// Example
final id = const Uuid().v7();
print(uuidV7ToDateTime(id)); // 2026-10-20 14:35:22.000

Choosing v4 vs v7 in Flutter

Use caseVersion
SQLite primary keyv7 — ORDER BY id = chronological
Offline sync queue recordv7 — replay in creation order
Hive box keyv7 — sorted keys = time order
Analytics event IDv7 — timestamp for session analysis
External-facing API tokenv4 — creation time not disclosed
Idempotency key for paymentsv4 — must be unpredictable
Widget ValueKey for stable listsEither — uniqueness is what matters

Further Reading

External References

Frequently asked questions

How do I generate a UUID in Flutter?

Add the uuid package to pubspec.yaml: uuid: ^4.0.0. Then call const Uuid().v4() for a random UUID v4 or const Uuid().v7() for a time-ordered UUID v7. Both return a standard hyphenated UUID string. No additional permissions or platform setup are needed on iOS or Android.

Does Flutter support UUID v7?

Yes. The uuid Dart package v4.0.0 and later provides Uuid().v7() which generates a time-ordered UUID v7 per RFC 9562. The timestamp uses DateTime.now().millisecondsSinceEpoch. UUID v7 is recommended over UUID v4 for SQLite primary keys in Flutter because lexicographic sort order equals insertion order — ORDER BY id returns rows in the order they were created.

How do I store a UUID as a primary key in sqflite?

Declare the column as TEXT NOT NULL PRIMARY KEY in your CREATE TABLE statement. SQLite has no native UUID type — store the UUID as a 36-character hyphenated string. Use UUID v7 so that ORDER BY id gives chronological order without a separate created_at index. The sqflite package documentation covers database initialisation and migration patterns.

What is the difference between Uuid().v4() and Uuid().v7() in Dart?

Uuid().v4() generates a random 128-bit UUID with no time component — each call produces an unordered identifier. Uuid().v7() embeds the current millisecond timestamp in the first 48 bits, making UUIDs sortable by creation time. Use v4 for external-facing identifiers where creation time should not be disclosed, and v7 for database primary keys, sync queue records, and any identifier where chronological ordering is useful. See UUID versions for a full comparison.

Can I use UUID v7 for offline-first sync in Flutter?

Yes — this is one of the strongest use cases. Generate UUID v7 on the device when the record is created offline. The 48-bit timestamp encodes when the record was created, so when multiple devices sync to the server, records merge in creation order without any server-side sequencing. The server can trust the timestamp embedded in the UUID v7 (within the device's clock accuracy) for ordering. See the offline sync section below for a complete implementation.