How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example
This example shows Learn how to generate Unique ID - GUID, UUID in Dart programming language with examples.
Related posts:
This tutorial uses uuid
🔗 package in dart and flutter.
UUID is a 16-Byte unique id with every 4 digits separated by a hyphen(-).
How to Install uuid packages in flutter and dart
First, Add the package to pubspec.yaml
.
This is a yaml file generated during project creation, else you can create a file
pubspec.yaml
uuid: ^3.0.6
added to the dependencies attribute in the file
name: dartapp
description: >-
dart example application.
version: 1.0.0
environment:
sdk: ">=2.10.0 <3.0.0"
dependencies:
uuid: ^3.0.6
Install the dependencies using the dart or flutter command Open a terminal window.
In the Dart project, run the dart pub get
command
In the flutter project, run the flutter pub get
command
PS A:\work\dart> dart pub get
Resolving dependencies...
+ Collection 1.16.0
+ crypto 3.0.1
+ typed_data 1.3.0
+ uuid 3.0.6
Changed 4 dependencies!
Once the dependencies are installed, Let’s write a dart program
How to Generate Unique id in Dart or Flutter
UUID package provides different versions of unique keys
uuid v1
: Generate unique id with timestamp-based logicuuid v2
: Generate Unique id with random id-based logicuuid v5
: Generate UUID with namespace sha1 logic- Import
package:uuid/uuid.dart
package into the program - create Uuid object.
- Call v1(),v2(),v5() functions of an object
Here is an example to Generate a unique or UUID key in the dart program.
import 'package:uuid/uuid.dart';
void main() {
var uuid = Uuid();
print(uuid.v1());//59976040-a675-11ec-8ee4-1f922f66b681
print(uuid.v4()); //38541b4a-26ee-4a4a-b0d6-e524254ff3b0
print(uuid.v5(Uuid.NAMESPACE_NIL,"cloudhadoop.com")); //499cd2aa-9aab-5c3d-aff5-7f12306f02fb
}
Output:
59976040-a675-11ec-8ee4-1f922f66b681
38541b4a-26ee-4a4a-b0d6-e524254ff3b0
499cd2aa-9aab-5c3d-aff5-7f12306f02fb
How to get Generate Empty UUID in dart and flutter?
Sometimes, We want to have an empty UUID to return from a method or function in dart or flutter. This has more advantages for type safety than null values.
- Import
uuid/uuid.dart
package into program - call NAMESPACE_NIL static member for Uuid class
- It returns Empty UUID with complete zeroes
Here is an example to generate an empty UUID program
import 'package:uuid/uuid.dart';
void main() {
const emptyUuid = Uuid.NAMESPACE_NIL;
print(emptyUuid);
}
Output:
00000000-0000-0000-0000-000000000000