Why is returning Instance of 'Future<String?>' instead String value?
Future<String?> getUser() async {
User user = await FirebaseAuth.instance.currentUser!;
FirebaseFirestore firestore = await FirebaseFirestore.instance;
String uid = user.uid;
String? userName;
// to get username from firebase
return firestore
.collection("users")
.doc(uid)
.get()
.then((value) {
if (value.exists) {
var data = value.data();
userName = data?["name"];
print("There is data :$userName");
} else {
print("There no Data!");
}
return Future.value(userName);
});
}
I am trying to get String value?
The place you like to get data from this method use await & the method is needed to be async. like
_myFunction() async{
final value = await getUser();
Also I will suggest to not mixing await and .then.
Future<String?> getUser() async {
User user = FirebaseAuth.instance.currentUser!;
FirebaseFirestore firestore = FirebaseFirestore.instance;
String uid = user.uid;
String? userName;
// to get username from firebase
final value = await firestore.collection("users").doc(uid).get();
if (value.exists) {
var data = value.data();
userName = data?["name"];
print("There is data :$userName");
} else {
print("There no Data!");
}
return userName;
}
Related
I have this code
checkUserValue(String user) async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
await _firestore.runTransaction((transaction) async {
DocumentReference userRef = _firestore
.collection("users")
.where("id", isEqualTo: "hhjhgjhfhgfhgfh");
DocumentSnapshot snapshot = await transaction.get(userRef);
String docc = snapshot.get("username");
print(docc);
if (docc == null) {
_userExist = false;
} else {
_userExist = true;
}
});
}
But am faced with this issue,
Please I need solution
where(...) function return Query<Map<String, dynamic>> not the DocumentReference
You need to pass the document path (DocumentReference) in the get() method. So, specify the correct document path
DocumentReference userRef = _firestore.collection('users').doc('hhjhgjhfhgfhgfh');
checkUserValue(String user) async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
await _firestore.runTransaction((transaction) async {
DocumentReference userRef =
_firestore.collection('users').doc('hhjhgjhfhgfhgfh');
DocumentSnapshot snapshot = await transaction.get(userRef);
String docc = snapshot.get('username');
print(docc);
if (docc == null) {
_userExist = false;
} else {
_userExist = true;
}
});
}
I have one user in my database:
Users {
userId: Xx1j9Pih4BPnu01vnFdMfZqGOr02: {name: 'jack5' ,phone: '0845204281'
}
}
So far I have the following function for getting data from the realtime firebase database.
static Future<dynamic> getCurrentUserInfo() async {
String? userId = FirebaseAuth.instance.currentUser?.uid;
final ref = FirebaseDatabase.instance.ref();
final snapshot = await ref.child('users/$userId').get();
if (snapshot.exists) {
return snapshot.value;
} else {
print('No data available.');
return '';
}
The function returns an object. How do I convert this object into a string? Or: How do I simply get the name of the current user of my database?
static Future<dynamic> getCurrentUserInfo() async {
String? userId = FirebaseAuth.instance.currentUser?.uid;
final ref = FirebaseDatabase.instance.ref();
final snapshot = await ref.child('users/$userId').get();
if (snapshot.exists) {
Map<dynamic, dynamic> values = needsSnapshot.value;
values.forEach((key, values) {
print(values['name']);
print(values['phone']);
});
} else {
print('No data available.');
return '';
}
}
If you just want to get the name property of the user, assuming your users are stored by their UID, that'd be:
final snapshot = await ref.child('users/$userId/name').get();
print(snapshot.value);
I tried this way, but i'm getting an error.
The error:
The method 'data' isn't defined for the type 'CollectionReference'. (undefined_method at [myapp] android\app\lib\useracc.dart:32)
void getData() async{
User? user = await FirebaseAuth.instance.currentUser;
var vari =FirebaseFirestore.instance.collection("users");
setState (() {
name = vari.data()['firstname'];
}
);
}
Signup/Register Page
Future<User?> _register(String fname,String lname ,String email, String password) async{
FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseFirestore _firestore = FirebaseFirestore.instance;
try {
UserCredential userCrendetial = await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text);
print("Account created Succesfull");
userCrendetial.user!.updateDisplayName(fname);
userCrendetial.user!.updateDisplayName(lname);
await _firestore.collection('users').doc(_auth.currentUser!.uid).set({
"firstname": fname,
"lastname" : lname,
"email": email,
"uid": _auth.currentUser!.uid,
});
return userCrendetial.user;
} catch (e) {
print(e);
return null;
}
}
This is the user account from where i want to fetch info:
Please help. I'm struck here a long time.
You should retrieve the currentUser document then access its data:
void getData() async{
var vari = await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser.uid)
.get();
setState (() {
name = vari.data()['firstname'];
});
}
if you've saved your user's details in firestore and its document id is the same as that of user ID (which is preferred for ease of access and control), then:
var vari =FirebaseFirestore.instance.collection("users").doc(user!.uid).get();
This gets the document of the user, and the type is DocumentSnapshot.
Map<String,dynamic> userData = vari as Map<String,dynamic>;
now userData is stored in form of Map. suppose you want to access their 'name', so the syntax now goes like userData['name'].
Similarly other fields can be accessed from variable. It's preferred to store userData in a Provider to access it's contents anywhere in your app.
Full code snippet
void getData() async{
User? user = await FirebaseAuth.instance.currentUser;
var vari =FirebaseFirestore.instance.collection("users").doc(user!.uid).get();
Map<String,dynamic> userData = vari as Map<String,dynamic>;
setState (() {
name = userData['firstname']; //or name = userData['name']
}
);
}
Hello I'm using flutter and firebase so I have firestore I have on collocation name Institutes and in document has names of Institutes and my Fields I have profile data ….no I need update some fields by where conditions where currant user = Key User id in the fields*
Screenshot
onPressed: ()async {
final FirebaseAuth auth = FirebaseAuth.instance;
final user = await auth.currentUser();
final iduser = user.uid;
final emailuser = user.email;
final snapshot = await Firestore.instance.collection("Institute")
.document(_Institute_name.text).get();
if (snapshot.exists) {
print(this name is existd);
} else {
await DataBaseService(email: emailuser,
uid: iduser,
Document: _Institute_name.text)
.CreateCollectionInofwithImage(
_Institute_name.text, Institute_address.text,
int.parse(Institute_phone.text), _image).then((isdone) {
setState(() {
Institute_address.clear();
Institute_phone.clear();
_Institute_name.clear();
_image = null;
});
});
}
}
Okay try this
onPressed: ()async {
final FirebaseAuth auth = FirebaseAuth.instance;
final user = await auth.currentUser();
final iduser = user.uid;
final emailuser = user.email;
QuerySnapshot snapshot = await Firestore.instance
.collection('Institute')
.where('user id', isEqualTo: iduser)//I think this is your field name from the
//picture it looks like theres a space in it
.getDocuments();
if (snapshot != null) {
Map<String,dynamic> document = snapshot.documents[0].data;
//Then you would reference this by document['fieldName']
} else {
await DataBaseService(email: emailuser,
uid: iduser,
Document: _Institute_name.text)
.CreateCollectionInofwithImage(
_Institute_name.text, Institute_address.text,
int.parse(Institute_phone.text), _image).then((isdone) {
setState(() {
Institute_address.clear();
Institute_phone.clear();
_Institute_name.clear();
_image = null;
});
});
}
}
Here is my code of a stateful class:
String id = FirebaseAuth.instance.currentUser().toString();
my function :
readLocal() async {
prefs = await SharedPreferences.getInstance();
id = prefs.getString('id') ?? '';
if (id.hashCode <= peerId.hashCode) {
groupChatId = '$id-$peerId';
} else {
groupChatId = '$peerId-$id';
}
setState(() {});
}
It works fine in String id.
I want the ID to be the same as the current user UID.
Calling FirebaseAuth.instance.currentUser() return a FirebaseUser, which is an object with all user data. If you only want the UID of the user:
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String uid = user.uid;
Update: I just ran this and it prints the UID for me:
void _getUser() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
print(user.uid);
}
Which printed:
flutter: P07IXLCrwEahYlDhzO1Iv0SKDat2
Things to notice:
In order to be able to use await in the code, the method must be marked as async.