Skip to content

Instantly share code, notes, and snippets.

@wilsonsilva
Last active August 1, 2023 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilsonsilva/cc1f612f45228bfad5837a19a317d2fc to your computer and use it in GitHub Desktop.
Save wilsonsilva/cc1f612f45228bfad5837a19a317d2fc to your computer and use it in GitHub Desktop.
Create a Firestore ID in Dart
import 'dart:math';
const _characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const _length = 28;
String createFirestoreId() {
return List.generate(_length, _randomCharacter).join();
}
String _randomCharacter(_) {
return _characters[Random.secure().nextInt(_characters.length)];
}
void main() {
print(createFirestoreId()); // Prints a string like 'UhN7eDazLYe8QNMdtyCVzNMrU1t1'
}
@wilsonsilva
Copy link
Author

DartPad: https://dartpad.dev/?id=cc1f612f45228bfad5837a19a317d2fc

Alternatively, you can use this hack by Luke Pighetti:

FirebaseStore.instance.rootRef.collection('fake').doc().id;

@wilsonsilva
Copy link
Author

nanoid2 does this neatly. cloud_firestore also does this, but it is not a public interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment