How to Update fields using where conditions Current user = Key ( User ID) firestore and flutter - flutter

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;
});
});
}
}

Related

Instance of 'Future<String?>' flutter

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;
}

How to pass uid and email to sharedpreference method When signUp in flutter?

I built the google signin and email password signup app using flutter,
I want when user log to application then user's "uid" and "email" save in shared preference.
In google login I built when login then pass the boolean value and pass uid and email to shared preference. Then when users close app and when reopen then login in home screen and can get uid and email.
But when user signup or login using email password then can not pass the boolean value and uid and email to google login shared preference. In below I'll mentioned google login method and email password method.
googlelogin method
// handling google sigin in
Future handleGoogleSignIn() async {
final sp = context.read<SignInProvider>();
final ip = context.read<InternetProvider>();
await ip.checkInternetConnection();
if (ip.hasInternet == false) {
openSnackbar(context, 'Check your Internet connection', Colors.red);
googleController.reset();
} else {
await sp.signInWithGoogle().then((value) {
if (sp.hasError == true) {
openSnackbar(context, sp.errorCode.toString(), Colors.white);
googleController.reset();
} else {
// checking whether user exists or not
sp.checkUserExists().then((value) async {
if (value == true) {
// user exists
await sp.getUserDataFromFirestore(sp.uid).then((value) => sp
.saveDataToSharedPreferences()
.then((value) => sp.setSignIn().then((value) {
googleController.success();
handleAfterSignIn();
})));
} else {
// user does not exist
sp.saveDataToFirestore().then((value) => sp
.saveDataToSharedPreferences()
.then((value) => sp.setSignIn().then((value) {
googleController.success();
handleAfterSignIn();
})));
}
});
}
});
}
//login function
}
saveDataToSharedPreferences method and setSignIn boolean value (it has in a siginprovider class in another file)
class SignInProvider extends ChangeNotifier {
//instantiate of firebaseAuth, facebook and google
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
bool _isSignedIn = false;
bool get isSignedIn => _isSignedIn;
//hasError, errorCode, provider,uid,email,name,imageUrl
bool _hasError = false;
bool get hasError => _hasError;
String? _errorCode;
String? get errorCode => _errorCode;
String? _uid;
String? get uid => _uid;
String? _email;
String? get email => _email;
SignInProvider() {
checkSignInUser();
}
Future checkSignInUser() async {
final SharedPreferences s = await SharedPreferences.getInstance();
_isSignedIn = s.getBool('signed_in') ?? false;
notifyListeners();
}
Future setSignIn() async {
final SharedPreferences s = await SharedPreferences.getInstance();
s.setBool('signed_in', true);
_isSignedIn = true;
notifyListeners();
}
Future saveDataToSharedPreferences() async {
final SharedPreferences s = await SharedPreferences.getInstance();
await s.setString('email', _email!);
await s.setString('uid', _uid!);
notifyListeners();
}
Future getDataFromSharedPreferences() async {
final SharedPreferences s = await SharedPreferences.getInstance();
_email = s.getString('email');
_uid = s.getString('uid');
notifyListeners();
}
}
**email password signup**
void signUp(String email, String password) async {
if (_formkey.currentState!.validate()) {
await _auth
.createUserWithEmailAndPassword(email: email, password: password)
.saveDataToSharedPreferences()
.sp.setSignIn()
.then((value) => {postDetailsToFirestore()})
.catchError((e) {
Fluttertoast.showToast(msg: e!.message);
});
}
}
in email password signup has postDetailsToFirestore method
postDetailsToFirestore() async {
// calling our fireStore
//calling our user model
// sending these values
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
User? user = _auth.currentUser;
UserModel userModel = UserModel();
if (user != null) {
//writing all the values
userModel.email = user?.email;
userModel.uid = user?.uid;
await firebaseFirestore
.collection("users")
.doc(user?.uid)
.set(userModel.toMap());
Fluttertoast.showToast(msg: "Account created successfully ");
Navigator.pushAndRemoveUntil(
(context),
MaterialPageRoute(builder: (context) => HomeScreen()),
(route) => false);
}
}
in email password signup I called
these 2 methods but show this error
when signup how to pass uid and emaill to saveDataToSharedPreferences method and pass sp.setSignIn() boolean like as in google signing?
You are trying to use method saveDataToSharedPreferences from Future class, not from auth. For fix this issue, call prefs from main object:
final result = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
result.saveDataToSharedPreferences()
.sp.setSignIn()
// etc.

How to query firestore in real time in flutter

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;
}
});
}

Flutter, firebase. I want to show my registration form data other than the email and password and connect to a unique uid

Register Screen On Pressed method given, I believe there is a problem with calling Firebase user = result.user
onPressed: () async {
if(_formKey.currentState.validate()){
setState(() => loading = true);
dynamic result = await _auth.registerWithEmailAndPassword(email, password);
FirebaseUser user = result.user;
await DatabaseService(uid: user.uid).newUserInfo(
_nameC.text,
_cityC.text,
_contactnoC.toString()
);
if(result == null) {
setState(() {
error = 'Please supply a valid email';
loading = false;
});
}}},
// Database backend
class DatabaseService {
final String uid;
DatabaseService ({this.uid});
final CollectionReference userdata2 = Firestore.instance.collection('UserData');
Future newUserInfo(String name, String city, String contactno) async {
return await userdata2.document(uid).setData({
'name' : name,
'city' : city,
'contactno' : contactno
});
}}
// authentication backend
// register with email and password
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
DatabaseService(uid: user.uid);
return _userFromFirebaseUser(user);
} catch (error) {
print(error.toString());
return null;
} }
// user.dart
class User {
final String uid;
User({this.uid});
}

How convert FirebaseUser to string in flutter?

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.