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?
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?
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
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();
In year 2020 you can do UniqueKey();
which is a built in class:
https://api.flutter.dev/flutter/foundation/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.
UniqueKey().toString()
to get a unique string literal that can be saved in database. The Flutter team has overriden the toString()
method of the UniqueKey
class to return the underlying id associated with the key, check here. –
Houppelande UniqueKey
in this answer There are some important things to understand about this class. –
Sy I use microseconds instead of milliseconds, which is much more accurate and there is no need to add any package.
String idGenerator() {
final now = DateTime.now();
return now.microsecondsSinceEpoch.toString();
}
000
at the back. –
Affiance for
loop (like when making a whole bunch of records in a row). Be careful since this may not be a guaranteed way to get unique values. –
Eclosion Besides from uuid, you can also try this to generate small unique keys:
https://pub.dev/packages/nanoid
They even have a collision calculator:
This method will generate unique Id similar to (-N4pvg_50j1CEqSb3SZt)
String getCustomUniqueId() {
const String pushChars =
'-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
int lastPushTime = 0;
List lastRandChars = [];
int now = DateTime.now().millisecondsSinceEpoch;
bool duplicateTime = (now == lastPushTime);
lastPushTime = now;
List timeStampChars = List<String>.filled(8, '0');
for (int i = 7; i >= 0; i--) {
timeStampChars[i] = pushChars[now % 64];
now = (now / 64).floor();
}
if (now != 0) {
print("Id should be unique");
}
String uniqueId = timeStampChars.join('');
if (!duplicateTime) {
for (int i = 0; i < 12; i++) {
lastRandChars.add((Random().nextDouble() * 64).floor());
}
} else {
int i = 0;
for (int i = 11; i >= 0 && lastRandChars[i] == 63; i--) {
lastRandChars[i] = 0;
}
lastRandChars[i]++;
}
for (int i = 0; i < 12; i++) {
uniqueId += pushChars[lastRandChars[i]];
}
return uniqueId;
}
I've built a scenario to generate a unique cryptographically secure random id. with 4 random generations id's
First 4 Alphabets from an alphabets list [a-z].
Middle 4 digits from a digits list [0-9].
DateTime 4 microseconds since epoch substring 8 - 12 because they change frequently.
Last 4 Alphabets from an alphabets list [a-z].
Screen Shots of Generated id's:
A Function to Call
randomIdGenerator() {
var ranAssets = RanKeyAssets();
String first4alphabets = '';
String middle4Digits = '';
String last4alphabets = '';
for (int i = 0; i < 4; i++) {
first4alphabets += ranAssets.smallAlphabets[
math.Random.secure().nextInt(ranAssets.smallAlphabets.length)];
middle4Digits +=
ranAssets.digits[math.Random.secure().nextInt(ranAssets.digits.length)];
last4alphabets += ranAssets.smallAlphabets[
math.Random.secure().nextInt(ranAssets.smallAlphabets.length)];
}
return '$first4alphabets-$middle4Digits-${DateTime.now().microsecondsSinceEpoch.toString().substring(8, 12)}-$last4alphabets';
}
Class for list
class RanKeyAssets {
var smallAlphabets = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z'
];
var digits = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
];
}
If you like MongoDB style ids you could consider this small package that will help create the object id:
https://pub.dev/packages/crossplat_objectid
import 'package:bson_objectid/bson_objectid.dart';
main() {
ObjectId id1 = new ObjectId();
print(id1.toHexString());
ObjectId id2 = new ObjectId.fromHexString('54495ad94c934721ede76d90');
print(id2.timestamp);
print(id2.machineId);
print(id2.processId);
print(id2.counter);
}
There is also https://pub.dev/packages/xid which is lock free and has a Unicity guaranteed for 16,777,216 (24 bits) unique ids per second and per host/process
import 'package:xid/xid.dart';
void main() {
var xid = Xid();
print('generated id: $xid');
}
To generate a unique ID you can use this code
import 'package:id_gen/id_gen.dart';
print(UuidV4Gen().get());
from the lightweight and well-tested Dart package https://pub.dev/packages/id_gen
© 2022 - 2024 — McMap. All rights reserved.