How to generate a Unique id, flutter
Asked Answered
T

6

6

I am making a todo app with notifications and am using flutter local notifications plugin, How do I generate a unique integer as id for a specific todo so that I can also cancel notification of that specific todo using that unique integer.

Trews answered 30/12, 2021 at 11:1 Comment(0)
N
17

You can use UniqueKey().hashCode() to get a unique int.
For example:

final notificationId = UniqueKey().hashCode()
// or you can use DateTime.now().millisecondsSinceEpoch
...
Numerical answered 30/12, 2021 at 11:4 Comment(2)
I knew Unique key wouldn't work but forgot to try hash code, thanks anywaysTrews
You don't need to put () after .hashCode — it's a propertyMccue
B
3

I mention some of methods how you can get unique id :-

use time stamps like this

DateTime.now().millisecondsSinceEpoch;

In year 2020 you can do UniqueKey();

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.

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

can use xid package which is lock free and has a Unicity guaranteed for 24 bits unique ids per second and per host/process

import 'package:xid/xid.dart';

void main() {
  var xid = Xid();
  print('generated id: $xid');

}
Beshore answered 30/12, 2021 at 11:15 Comment(2)
Uuid does not return an int as required by the flutter notifications plugin.Numerical
okay I wil update my answerBeshore
S
1

You can use the following class:

class UuidUtil {
  static int get uuid => DateTime.now().microsecondsSinceEpoch;
}

And access it by:

final id = UuidUtil.uuid;
Sparling answered 17/8, 2023 at 6:19 Comment(0)
H
-1

To generate a unique integer ID you can use this code

import 'package:id_gen/id_gen_helpers.dart';

final idInt = genUuid.hash();                    // 2^64 native
final idIntShort = genUuid.hash() & 0xFFFFFFFF;  // 2^32
final idIntShortest = genUuid.hash() & 0xFFFF;   // 2^16

from the lightweight and well-tested Dart package https://pub.dev/packages/id_gen

Historical answered 21/1 at 19:19 Comment(0)
A
-2

You can used UUID package here

import 'package:uuid/uuid.dart';

 var uuid = Uuid();
 print(uuid.v1());  

 print(uuid.v4()); 

Or refer this also

Arrington answered 30/12, 2021 at 11:10 Comment(1)
This will not give an int as required by the flutter notifications plugin.Numerical
A
-3

You can use this package: http://pub.dartlang.org/packages/uuid

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(); // -> '120ec61a-a0f2-4ac4-8393-c866d813b8d1'

Ambrosio answered 30/12, 2021 at 11:9 Comment(1)
Uuid does not return an int as required by the flutter notifications plugin.Numerical

© 2022 - 2024 — McMap. All rights reserved.