not able to save information to firebase - firebase

I m tring to save course details from the filled form to firebase-database by calling the below function but I m getting some error. Here is a part of my code:
Future<void>saveCourseDataToDb(courseName, courseDescription,coursePrice,yearsOfExp, cities) async{
var timeStamp = Timestamp.now().microsecondsSinceEpoch;
FirebaseUser teacher= FirebaseAuth.instance.currentUser as FirebaseUser;
CollectionReference _courses = Firestore.instance.collection('courses');
try{
_courses.document(timeStamp.toString()).setData({
'tutor': {'TeacherName': this.TeacherName, 'Teacherid': teacher.uid },
'courseName': courseName,
'courseDescription': courseDescription,
'coursePrice': coursePrice,
'yearsOfExp': yearsOfExp,
'cities': cities,
'category' : {'categoryName': this.selectedCategory, 'categoryImage': this.categoryImage},
//'certificate': certificate,
'published': false,
'courseId': timeStamp.toString(),
'courseImage': this.courseURL,
'certificate' : this.certificateURL
});
ErrorAlertDialog(message: 'Course Details saved successfully',);
}catch(e){
ErrorAlertDialog(message: '${e.toString()}',);
}
return null;
}
I get this error:
And when I declare teacher with Future I get an error related to uid, here is a picture about the same.
Any help would be really appreciated!!

FirebaseUser is a Future, which means you have to "wait" for it to arrive. Try like this
FirebaseUser teacher = await FirebaseAuth.instance.currentUser;

instead of using
Future<FirebaseUser>
use
Future<User>
FirebaseUser has been changed to User long time ago & also use await before FirebaseAuth.instance.currentUser;
hope this may work 🙋‍♂️.

try this
first update your firebase plugin to latest version and pub get
then use this
final FirebaseAuth teacher = FirebaseAuth.instance.currentUser;
inplace of Future line
hope this time it works 🤞

Related

Error: 'currentUser' isn't a function or method and can't be invoked [duplicate]

This question already has answers here:
Undefined class 'FirebaseUser'
(6 answers)
Closed 2 years ago.
I just updated Google Firebase Auth in Flutter app because I was getting some wried SDK errors but now I'm getting:
Error: 'currentUser' isn't a function or method and can't be invoked.
User currentFirebaseUser = await FirebaseAuth.instance.currentUser();
I looked at the migration guide and understand that currentUser() is now synchronous via the currentUser getter. but I'm not sure how I should change my code now to fix this.
static void getCurrentUserInfo() async{
User currentFirebaseUser = await FirebaseAuth.instance.currentUser();
String userid = currentFirebaseUser.uid;
DatabaseReference userRef = FirebaseDatabase.instance.reference().child('users/$userid');
userRef.once().then((DataSnapshot snapshot){
if(snapshot.value != null){
}
});
}
you need to remove await and change currentUser() to currentUser.
So
User currentFirebaseUser = await FirebaseAuth.instance.currentUser();
Becomes
User currentFirebaseUser = FirebaseAuth.instance.currentUser;
Source: Verify email link and sign in
Let me know if this works ^_^
Its done like this :
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userid = user.getUid();

Cloud Firestore Read Quota [duplicate]

there guys, I do have an interesting problem here and I would be really glad if any of you it will be able to help me with that.
What's my app flow:
Register with the email, password and some other details:
User firebase in order to auth the user and create an account via email and password, at the same time I'm writing the custom data of the user to the database.
Log in the user.
That's it, that's all my basic logic, and how you can see I'm not doing any reading from the DB so far as I know.
Now... the problem is that from some weird reason when I'm registering my user I'm going to the firebase console to see the usage of my DB and I will see something like... for one user which was created I will have 1 write (which is fine as I was expected) but also 13-20 READS FROM DB.
Now that's my question, WHY on earth I have reads on firestorm when I'm doing just auth and writes?
Here it's my DB code which I'm using right now.
class DatabaseFirebase implements BaseDataBase {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseStorage _storage = FirebaseStorage.instance;
FirebaseUser _firebaseUser;
Firestore _firestore = Firestore.instance;
#override
Future<String> login(String email, String password) async {
_firebaseUser = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _firebaseUser.uid;
}
#override
Future<String> register(String email, String password) async {
_firebaseUser = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
return _firebaseUser.uid;
}
#override
Future<UserData> getCurrentUser() async {
if (_firebaseUser == null)
_firebaseUser = await _firebaseAuth.currentUser();
UserData user = UserData();
user.email = _firebaseUser?.email;
user.name = _firebaseUser?.displayName;
return user;
}
#override
Future<void> logout() async {
_firebaseAuth.signOut();
}
#override
Future<void> onAuthStateChanged(void Function(FirebaseUser) callback) async {
_firebaseAuth.onAuthStateChanged.listen(callback);
}
#override
Future<void> writeUser(UserData user) async {
_firestore.collection("Users").add(user.toMap()).catchError((error) {
print(error);
});
}
}
If some of you know could you explain to me where/how I need to search in order to find this bug? Because how you can see I'm not using any read what so ever.
It's impossible to know for sure given that we don't understand all possible routes of access into your database, but you should be aware that use of the Firebase console will incur reads. If you leave the console open on a collection/document with busy write activity, the console will automatically read the changes that update the console's display. This is very often the source of unexpected reads.
Without full reproduction steps of exactly all the steps you're taking, there's no way to know for sure.
Firebase currently does not provide tools to track the origin of document reads. If you need to measure specific reads from your app, you will have to track that yourself somehow.

Flutter place filter based on variable in firestore request

I am working on an app which requests based on the registered Userid certain elements from my firestore.
Now i'm trying to build the Notifier related to this but somehow it breaks when putting the filter in the firestore request
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:tutora/states/question_notifier.dart';
import 'package:tutora/models/answers.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<String> id() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String userID = user.uid.toString();
return userID;
}
getAnswers(AnswerNotifier answerNotifier) async {
QuerySnapshot snapshot = await Firestore.instance
.collection('Questions')
.where(
'UserID',
isEqualTo: await id(),
)
.getDocuments();
List<Answer> _answerList = [];
snapshot.documents.forEach((document) {
Answer answer = Answer.fromMap(document.data);
_answerList.add(answer);
});
answerNotifier.answerList = _answerList;
}
What in my head this should do is that it gets the current user ID and then based on that ones only collects the Questions which match on the column UserID.
This works perfectly fine if i manually enter the UserID in my code however the moment where it requests the current user ID from id() it does not find any matching questions. So my question list in the app is empty as well as ofc my _answerList here.
The user is logged in at this point in the app where this Answernotifier is called.
Thankful for any help this is really bugging me now quit some time.
Try the following:
getAnswers(AnswerNotifier answerNotifier) async {
String userId = await id();
QuerySnapshot snapshot = await Firestore.instance
.collection('Questions')
.where('UserID',isEqualTo: userId).getDocuments();
get the userId first and then use the result inside the where() query.

Google Firestore Database: Where are phantom document reads coming from? [duplicate]

there guys, I do have an interesting problem here and I would be really glad if any of you it will be able to help me with that.
What's my app flow:
Register with the email, password and some other details:
User firebase in order to auth the user and create an account via email and password, at the same time I'm writing the custom data of the user to the database.
Log in the user.
That's it, that's all my basic logic, and how you can see I'm not doing any reading from the DB so far as I know.
Now... the problem is that from some weird reason when I'm registering my user I'm going to the firebase console to see the usage of my DB and I will see something like... for one user which was created I will have 1 write (which is fine as I was expected) but also 13-20 READS FROM DB.
Now that's my question, WHY on earth I have reads on firestorm when I'm doing just auth and writes?
Here it's my DB code which I'm using right now.
class DatabaseFirebase implements BaseDataBase {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseStorage _storage = FirebaseStorage.instance;
FirebaseUser _firebaseUser;
Firestore _firestore = Firestore.instance;
#override
Future<String> login(String email, String password) async {
_firebaseUser = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _firebaseUser.uid;
}
#override
Future<String> register(String email, String password) async {
_firebaseUser = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
return _firebaseUser.uid;
}
#override
Future<UserData> getCurrentUser() async {
if (_firebaseUser == null)
_firebaseUser = await _firebaseAuth.currentUser();
UserData user = UserData();
user.email = _firebaseUser?.email;
user.name = _firebaseUser?.displayName;
return user;
}
#override
Future<void> logout() async {
_firebaseAuth.signOut();
}
#override
Future<void> onAuthStateChanged(void Function(FirebaseUser) callback) async {
_firebaseAuth.onAuthStateChanged.listen(callback);
}
#override
Future<void> writeUser(UserData user) async {
_firestore.collection("Users").add(user.toMap()).catchError((error) {
print(error);
});
}
}
If some of you know could you explain to me where/how I need to search in order to find this bug? Because how you can see I'm not using any read what so ever.
It's impossible to know for sure given that we don't understand all possible routes of access into your database, but you should be aware that use of the Firebase console will incur reads. If you leave the console open on a collection/document with busy write activity, the console will automatically read the changes that update the console's display. This is very often the source of unexpected reads.
Without full reproduction steps of exactly all the steps you're taking, there's no way to know for sure.
Firebase currently does not provide tools to track the origin of document reads. If you need to measure specific reads from your app, you will have to track that yourself somehow.

Firestore - unexpected reads

there guys, I do have an interesting problem here and I would be really glad if any of you it will be able to help me with that.
What's my app flow:
Register with the email, password and some other details:
User firebase in order to auth the user and create an account via email and password, at the same time I'm writing the custom data of the user to the database.
Log in the user.
That's it, that's all my basic logic, and how you can see I'm not doing any reading from the DB so far as I know.
Now... the problem is that from some weird reason when I'm registering my user I'm going to the firebase console to see the usage of my DB and I will see something like... for one user which was created I will have 1 write (which is fine as I was expected) but also 13-20 READS FROM DB.
Now that's my question, WHY on earth I have reads on firestorm when I'm doing just auth and writes?
Here it's my DB code which I'm using right now.
class DatabaseFirebase implements BaseDataBase {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseStorage _storage = FirebaseStorage.instance;
FirebaseUser _firebaseUser;
Firestore _firestore = Firestore.instance;
#override
Future<String> login(String email, String password) async {
_firebaseUser = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _firebaseUser.uid;
}
#override
Future<String> register(String email, String password) async {
_firebaseUser = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
return _firebaseUser.uid;
}
#override
Future<UserData> getCurrentUser() async {
if (_firebaseUser == null)
_firebaseUser = await _firebaseAuth.currentUser();
UserData user = UserData();
user.email = _firebaseUser?.email;
user.name = _firebaseUser?.displayName;
return user;
}
#override
Future<void> logout() async {
_firebaseAuth.signOut();
}
#override
Future<void> onAuthStateChanged(void Function(FirebaseUser) callback) async {
_firebaseAuth.onAuthStateChanged.listen(callback);
}
#override
Future<void> writeUser(UserData user) async {
_firestore.collection("Users").add(user.toMap()).catchError((error) {
print(error);
});
}
}
If some of you know could you explain to me where/how I need to search in order to find this bug? Because how you can see I'm not using any read what so ever.
It's impossible to know for sure given that we don't understand all possible routes of access into your database, but you should be aware that use of the Firebase console will incur reads. If you leave the console open on a collection/document with busy write activity, the console will automatically read the changes that update the console's display. This is very often the source of unexpected reads.
Without full reproduction steps of exactly all the steps you're taking, there's no way to know for sure.
Firebase currently does not provide tools to track the origin of document reads. If you need to measure specific reads from your app, you will have to track that yourself somehow.

Resources