'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?
Solution 1:[1]
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.
Solution 2:[2]
Besides from uuid, you can also try this to generate small unique keys:
https://pub.dev/packages/nanoid
They even have a collision calculator:
Solution 3:[3]
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();
}
Solution 4:[4]
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);
}
Solution 5:[5]
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');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BIS Tech |
| Solution 2 | theredforest |
| Solution 3 | dev001 |
| Solution 4 | 34m0 |
| Solution 5 | Bwire |
