How to generate UUID in dart / flutter

UUID in flutter

Very often, we come across the need to have UUID. UUIDs are perfect for giving unique ID to objects and resources. In this tutorial, we will see how to create UUID in dart for a flutter app.

Generating the UUID

Step 1: Add the uuid library to your project

To create UUIDs, we need to add the uuid library into the project. It can be added by inserting the following entry into your project’s pubsec.yaml file.

  uuid: 3.0.6

Step 2: Import “uuid/uuid.dart” and use it

Now, let’s use the added library to create UUID. First, import the library and then use it. Simply create an object of the Uuid() class and then use the provided v1(), v2(), v3(), v4(), or v5() function based on the UUID version you need. All the standard UUID versions are supported in this library.

import 'package:uuid/uuid.dart';
...
createUuid() {
  const uuid = Uuid();
  //Create UUID version-4
  return uuid.v4();
}
import 'package:uuid/uuid.dart';

createV5Uuid() {
  return Uuid().v5(Uuid.NAMESPACE_URL, 'www.genuinecoder.com');
}

If you are looking for more customized UUIDs with more control over the random data, have look into the library example section.

Create Unique ID without additional libraries

Now, let’s say you don’t need UUID exactly, but want unique auto-generated IDs. Then you can proceed with the UniqueKey class.

UniqueKey() will return an alphanumeric string (usually 5 char length).

createUUID() {
  return UniqueKey();
}

Conclusion

In this tutorial, we have seen how to generate UUID with flutter. The UUID library supports all the standard variations and is straightforward to use. If you have liked this article, have a look into the other flutter tutorials I have written.

Muhammed Afsal Villan
Muhammed Afsal Villan is an experienced full-stack developer, specialized in desktop and mobile application development. He also regularly publishes quality tutorials on his YouTube channel named 'Genuine Coder'. He likes to contribute to open-source projects and is always enthusiastic about new technologies.

24 COMMENTS