Reputation: 45
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<void> userSetup(String displayName) async{
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
CollectionReference users = FirebaseFirestore.instance.collection("Users");
users.add({
'displayName': displayName,
'uid': uid,
// 'docID': docID,
});
return;
}
Just to preface, I'm a complete beginner with Flutter.
This is what I'm using to add the collection in Firestore but I'd like to retrieve the the specific document ID and use it for further storage. Is there a method to obtain and store the document ID in the user details? I'm trying to retrieve the specific user's name when they login and display it on the homepage.
Upvotes: 0
Views: 1076
Reputation: 138
In the case that you do not want to use custom IDs for your documents but instead rely on firebase auto generated IDs you can do the following.
Future<void> userSetup(String displayName) async {
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
CollectionReference users = FirebaseFirestore.instance.collection("Users");
users.doc(uid).set({
'displayName': displayName,
});
return;
}
This will set the document ID to be the same as the users uid. The benefit of this approach is two fold.
Upvotes: 0
Reputation: 1
At runtime, components are able to read the contents of their own package by accessing the path /pkg/ in their namespace. The resource() template may be used to add contents to the package that may be accessed this way.
Upvotes: -1
Reputation: 154
You may try this method
Preset the document id with your own, you may use the package uuid https://pub.dev/packages/uuid
or use the user's uid as the doc id
//final docID = Uuid().v4(); //use custom uuid for doc id
//final docID = uid; //use user id as doc id
users.doc(docID).set({
'displayName': displayName,
'uid': uid,
});
Then save the docID to user device with shared_preferences for persistant storage https://pub.dev/packages/shared_preferences
Upvotes: 1
Reputation: 1
You can retrieve **firestore** doc id only when you retrieve the data using a stream builder. Take a look at the code.
Streambuilder(
stream: Firestore.instance.collection("Your collection").snapshot(),
builder: (context,snapshot) {
if(snapshot.hasData) {
List<User> users = []
for(var doc in sanpshot.data.documents) {
users.add(
new User(
name: doc.data["name"],
email: doc.data["email"]
**id: doc.documentID**
)
)
return Column(
children: users
)
}
}
}
)
Upvotes: 0
Reputation: 598901
If you want to store the ID inside the document, you can first create the DocumentReference
for the new document by calling CollectionReference.doc()
without parameters:
CollectionReference users = FirebaseFirestore.instance.collection("Users");
var newDocRef = users.doc();
var newDocId = newDocRef.id
users.add({
'displayName': displayName,
'uid': uid,
'docID': newDocId
});
Upvotes: 0