Skip to content

Generating UUIDs in Dart and Flutter

Flutter, Dart, UUID, Mobile Development1 min read

UUIDs (Universally Unique Identifiers) are useful for differentiating data. In this article, we'll explore how to generate random UUIDs in Flutter using Dart.

Using the uuid Package

The uuid package provides a straightforward way to create UUIDs. Let's get started:

  1. Add the Package First, add the uuid package to your pubspec.yaml file:

    2 uuid: ^4.4.0
  2. Import the Library Import the uuid package in your Dart file:

    1import 'package:uuid/uuid.dart';
  3. Generate UUIDs Create an instance of the Uuid class to generate UUIDs:

    • To generate a v1 (time-based) UUID:

      1var uuid = Uuid();
      2var timeBasedId = uuid.v1(); // Example: '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
    • To generate a v4 (random) UUID:

      1var randomId = uuid.v4(); // Example: '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
    • To generate a v5 (namespace-name-sha1-based) UUID:

      1var namespaceUrl = Uuid.NAMESPACE_URL;
      2var name = '';
      3var namespaceBasedId = uuid.v5(namespaceUrl, name); // Example: 'c74a196f-f19d-5ea9-bffd-a2742432fc9c'

Wrapping Up

Now you know how to generate UUIDs in Dart/Flutter using the uuid package. Feel free to use these unique identifiers in your applications! 🚀

For more complex examples and additional usages, explore the package's documentation and tests. Happy coding! 😊