First of all i will be highly thankful to stackoverflow community you guys are great. Problem: i am using namecontroller for firebase username and password is
TextEditingController nameController = TextEditingController();
TextEditingController passwordController = TextEditingController();
and here is authentication with firebase
final user = await _auth.signInWithEmailAndPassword(
email: nameController.text,
password: passwordController.text);
and here is code through i will save gps data to firebase firestone database
final loc.LocationData _locationResult = await location.getLocation();
await FirebaseFirestore.instance.collection('location').doc('user1').set({
'latitude': _locationResult.latitude,
'longitude': _locationResult.longitude,
'name': 'Bus No.1'
}, SetOptions(merge: true));
as .doc is created with name user1 and 'name' : 'Bus No.1' i want to replace .doc firebase with username or namecontroller previously i used and also name field with same username is it possible because lot of other user using this app so database save data separetely. Thanks
CodePudding user response:
Why not pass the value to your function?
Future<void> setUserData(String docId, String name) async {
final loc.LocationData _locationResult = await location.getLocation();
await FirebaseFirestore.instance.collection('location').doc(docId).set({
'latitude': _locationResult.latitude,
'longitude': _locationResult.longitude,
'name': name
}, SetOptions(merge: true));
}
Then call the function and pass the value in the controller, like this:
setUserData(user.id, nameController.text);
CodePudding user response:
So, It'll be better to save the document by userId which is unique for each user, hence avoiding reputation. It can be accessed using -
User? user = FirebaseAuth.instance.currentUser;
String uid = user!.uid;
So let's create the document for this user in Firestore!
/// from above example
User? user = FirebaseAuth.instance.currentUser;
String uid = user!.uid;
///name of user using nameController
String name = nameController.text;
final loc.LocationData _locationResult = await location.getLocation();
await FirebaseFirestore.instance.collection('location').doc(uid).set({
'latitude': _locationResult.latitude,
'longitude': _locationResult.longitude,
'name': name <-- from TextEditingController()
}, SetOptions(merge: true));
Congrats, you just made a firestore document with document-id same as that of user-id, which is unique and set a name property which could be used within your app.
now if you want to access name of current user,
String uid = FirebaseAuth.instance.currentUser!.uid; <-- null check is required
DocumentSnapshot document = FirebaseFirestore.instance.collection('location').doc(uid).get();
Map<String, dynamic> data = document.doc() as Map<String, dynamic>;
///lets say you want to get name
var name = data['name'];
read further by following this guide -> https://firebase.google.com/docs/firestore/query-data/get-data