I'm trying to refactor my code to reduce Firebase read operations. For this I'm using Sharedpreferences. The code is structured in such a way that there's a provider that take's care of the update process and saves the new values in shared preferences. Here is the code.
submit() async {
final User user = _auth.currentUser;
DocumentReference ref =
FirebaseFirestore.instance.collection('users').doc(user.uid);
final prefs = await SharedPreferences.getInstance();
try {
if (_image != null){
mediaurl= await uploadImage();
await ref.update({"MediaURL": mediaurl});
prefs.setString("MediaURL", mediaurl);
}
if(username!=null){
ref.update({"username":userNamecontroller.text});
prefs.setString('username', username);
}
if(description!=null){
ref.update({"description":descriptionController.text});
prefs.setString('description', description);
}
} catch (e) {print("tHE ERROR IS $e");}
notifyListeners();
}
The problem however is the submit function does not work. No data is updated to firebase and the error from my catch block is
tHE ERROR IS NoSuchMethodError: The getter 'absolute' was called on null.
Any ideas what this 'absolute' is?
Related
I am trying to get user email,save to shared preferences and use as collection name in another file.
my code to save
Future<void> saveEmail() async {
var sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString("email", _emailKontroller.text);}
no problem here, I can save data to sharedPreferences and read data from another file.
my code to read
#override
void initState() {
// TODO: implement initState
void initilaizeEmail() async {
var sharedPreferences = await SharedPreferences.getInstance();
_email = sharedPreferences.getString("email");
print(_email);
}
initilaizeEmail();
setState(() {});
}
output
I/flutter ( 3274): a#a.com
where I use as parameter my sharedPreferences Data:
query: FirebaseFirestore.instance
.collection("test")
.doc("$_email")
.collection("class 0"),
// to fetch real-time data
isLive: false,
I can not see anything on screen but, if I delete
_email
and type "a#a.com" manually everything works.What is the problem?
The problem is that initilaizeEmail is an async method, and you're not waiting for its result. To fix this:
await initilaizeEmail();
I also recommend fixing the name of the method to be initializeEmail. While it won't change the behavior, spelling mistakes tend distract from other problems.
I solved my problem with using
Future Builder
I am learning Firebase with Flutter.
Currently making an anonymous login option, here is the class I created:
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// sign in anonymously
Future signInAnonymous() async {
try{
// signs in as anon user
AuthResult signInResult = await _auth.signInAnonymously();
// retruns currently signed in user, else null
FirebaseUser userFromResult = signInResult.user;
return userFromResult; // HERE: if I add .uid, the id object is displayed
}catch(e){
print(e.toString());
return null;
}
}
}
In my login page after creating an instance and using the method, when I print the result I get FirebaseUser(Instance of 'PlatformUser') insted of the user information, here is the code:
onPressed: () async {
dynamic result = await _auth.signInAnonymous();
if(result == null){print('Error signing in.');}
else{
print('Signed in successfully');
print(result);
}
How can I access the user data?
UPDATE: If I change return userFromResult; to return userFromResult.uid; the id string is returned.
I still wonder, however, how to print the full object.
Your Result inside of the onpressed is a dynamic type cast, but it is a FirebaseUser inside.
// onPressed Callback
dynamic result = await _auth.signInAnonymous();
You can change your SignIn method with the right return type and use instead of dynamic the FirebaseUser.
Future<FirebaseUser> signInAnonymous() async {
// [...]
return userFromResult; // HERE: if I add .uid, the id object is displayed
}
onPressed: () async {
FirebaseUser result = await _auth.signInAnonymous();
print(result.uid); // should contain the id
// [...]
The difference is that in version 0.13.x the user data is available, but in the version used in this example the bersion used is 0.16.x.
I've been having a problem trying to update data from a logged in user. I have the uid, but there has to be a connection between the uid and the collection of users, so that the program picks the right user to update, but I don't know how to make it.
Here's what I have:
FirebaseUser loggedInUser;
final _firestore = Firestore.instance;
//
double _latitude;
double _longitude;
void getCurrentLocation() async {
try {
Position position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
setState(() {
_latitude = position.latitude;
_longitude = position.longitude;
});
_firestore
.collection('users')
.document('${loggedInUser.uid}')
.updateData({'location': GeoPoint(_latitude, _longitude)});
} catch (e) {
print(e);
}
}
Here's what I've been getting:
E/flutter ( 9187): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(Error performing updateData, NOT_FOUND: No document to update: projects/app-#####/databases/(default)/documents/users/CGyByl58ELc0zirlVjJpv5OWAc42, null)
So it is using the right uid ("CGyByl58ELc0zirlVjJpv5OWAc42")
Here's a screenshot from the Authentication tab of Firebase:
But what I'm trying to get is the name of the collection of this user in the database:
The user id is different than the document id, that's why you get that error since no document exists with the userId. You need to use the userId as the document id:
void addUser() async{
var firebaseUser = await FirebaseAuth.instance.currentUser();
Firestore.instance.collection("users").document(firebaseUser.uid).setData(
{
"age" : 38,
}).then((_){
print("success!");
});
}
Now you will have the userId as the document id and you can update the document using the userId
I am developing on the flutter platform and using FirebaseAuth library for dart.
When I call FirebaseAuth.signInWithEmailAndPassword(), the user returned in the AuthResult is null.
The problem is that no error was thrown. So I am really confused. According to the docs, there is a list of error code that can be thrown. But in this instance it is just silently failing. Does anyone know why it could be silently failing without communicating any sort of error back?
My code looks as follows...
try {
final AuthResult result = await FirebaseAuth.instance.signInWithEmailAndPassword(
email:email,
password:password
);
final FirebaseUser user = result.user;
if (user != null) {
callback(RequestUserSignInResult.Fail);
return;
}
_user = user;
callback(RequestUserSignInResult.Success);
}
catch (e) {
print("CODE:"+e.code+'\n');
print("MESSAGE:"+e.message+'\n');
callback(RequestUserSignInResult.Success);
}
You seem to have reversed your conditions when checking for the presence of a user in the AuthResult response. But you could also simplify your code like this:
try {
FirebaseAuth.instance.signInWithEmailAndPassword(
email:email,
password:password
).then((authResult){
if(authResult.user != null){
_user = authResult.user;
callback(RequestUserSignInResult.Success);
}else{
callback(RequestUserSignInResult.Fail);
}
});
} catch (e) {
print("CODE:"+e.code+'\n');
print("MESSAGE:"+e.message+'\n');
callback(RequestUserSignInResult.Fail);
}
I'm trying to check whether the user is signed in or not, I've authenticated my flutter app with firebase, I want the status of the user to redirect the app to either login page or home page, but I can't run the app it shows the error on red screen and the error is:
NoSuchMethodError: The method 'currentUser' was called on null.
Receiver: null
Tried calling: currentUser()
I saw the solution here
but I did not understood it properly
currentUser function:
Future<String> currentUser() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user!= null ? user.uid : null;
}
checking the authentication status:
void initState() {
super.initState();
try {
widget.auth.currentUser().then((userId) {
setState(() {
authStatus =
userId == null ? AuthStatus.notsignedIn : AuthStatus.signedIn;
});
});
} catch (e) {}
}
The error just means that your _firebaseAuth object is null. Try using
FirebaseUser user = await FirebaseAuth.instance.currentUser();