Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate unique id in Dart

I write websocket chat. How to generate unique id for user?

now i use this code:

id = new DateTime.now().millisecondsSinceEpoch; 

is there any more neat solution?

like image 927
Sergey Karasev Avatar asked Mar 21 '13 13:03

Sergey Karasev


People also ask

How do I get UUID flutter?

If you need only the id of the device that your app is running on, the simplest and quickest solution is to use the platform_device_id package. It works on Android (AndroidId), iOS (IdentifierForVendor), Windows (BIOS UUID), macOS (IOPlatformUUID), and Linux (BIOS UUID).

What is UUID generator?

A UUID (Universal Unique Identifier) is a 128-bit value used to uniquely identify an object or entity on the internet. Depending on the specific mechanisms used, a UUID is either guaranteed to be different or is, at least, extremely likely to be different from any other UUID generated until A.D. 3400.


2 Answers

1. There is a UUID pub package:

http://pub.dartlang.org/packages/uuid

example usage:

import 'package:uuid/uuid.dart';  // Create uuid object var uuid = Uuid();  // Generate a v1 (time-based) id uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'  // Generate a v4 (random) id uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'  // Generate a v5 (namespace-name-sha1-based) id uuid.v5(uuid.NAMESPACE_URL, 'www.google.com'); // -> 'c74a196f-f19d-5ea9-bffd-a2742432fc9c' 

2. This src has a dart GUID generator

https://github.com/MikeMitterer/AndroidIconGenerator.DART/blob/445884924/lib/src/model/communication/GUIDGen.dart

I'll not post the function src here directly as there is no apparent licence with it, but example usage is as follows:

final String uuid = GUIDGen.generate(); 
like image 111
Chris Buckett Avatar answered Sep 28 '22 04:09

Chris Buckett


In year 2020 you can do UniqueKey(); which is a built in class:

https://api.flutter.dev/flutter/widgets/UniqueKey-class.html

Note

A key that is only equal to itself.

This cannot be created with a const constructor because that implies that all instantiated keys would be the same instance and therefore not be unique.

like image 21
Pascal Avatar answered Sep 28 '22 05:09

Pascal