I am trying to get an image from the storage and use the url for a default profile picture but i am getting this error.
firebase_storage/object-not-found No object exists at the desired reference.
This is my code.
void authenticateStudent() async {
User? currentStudent;
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
await firebaseAuth
.createUserWithEmailAndPassword(
email: umailController.text.trim(),
password: passwordController.text.trim(),
)
.then((auth) {
currentStudent = auth.user;
}).catchError((onError) {
print(onError);
});
if (currentStudent != null) {
FirebaseStorage.instance
.ref()
.child('profile')
.getDownloadURL()
.then((url) {
imageUrl = url;
});
saveDataToFirestore(currentStudent!).then((value) {
Navigator.pop(context);
print("User added successfully");
});
}
}
Future saveDataToFirestore(User currentStudent) async {
FirebaseFirestore.instance
.collection("students")
.doc(currentStudent.uid)
.set({
"studentUID": currentStudent.uid,
"fname": fnameController.text.trim(),
"lname": lnameController.text.trim(),
"Mobile": phoneController.text.trim(),
"Program": selectedProgram,
"student_id": studentidController.text.trim(),
"cohort": selectedCohort,
"umail": currentStudent.email,
"profilepicture": imageUrl,
"active": active,
"status": status
});
}
The database is structured like this
This is my code.
void authenticateStudent() async {
User? currentStudent;
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
await firebaseAuth
.createUserWithEmailAndPassword(
email: umailController.text.trim(),
password: passwordController.text.trim(),
)
.then((auth) {
currentStudent = auth.user;
}).catchError((onError) {
print(onError);
});
if (currentStudent != null) {
FirebaseStorage.instance
.ref()
.child('profile')
.getDownloadURL()
.then((url) {
imageUrl = url;
});
saveDataToFirestore(currentStudent!).then((value) {
Navigator.pop(context);
print("User added successfully");
});
}
}
Future saveDataToFirestore(User currentStudent) async {
FirebaseFirestore.instance
.collection("students")
.doc(currentStudent.uid)
.set({
"studentUID": currentStudent.uid,
"fname": fnameController.text.trim(),
"lname": lnameController.text.trim(),
"Mobile": phoneController.text.trim(),
"Program": selectedProgram,
"student_id": studentidController.text.trim(),
"cohort": selectedCohort,
"umail": currentStudent.email,
"profilepicture": imageUrl,
"active": active,
"status": status
});
}
The database is structured like this
Your code says:
FirebaseStorage.instance
.ref()
.child('profile')
.getDownloadURL()
But in the screenshot, the file is called profile.png. The path must match completely and exactly, so:
FirebaseStorage.instance
.ref()
.child('profile.png')
.getDownloadURL()
Related
how to put the user id in this code when I am generating a to-do list and i need to retrieve the tasks that a certain user?
Future<void> create(String todo, String description) async {
try {
await firestore.collection("Todo").add({
'todo': todo,
'description': description,
'timestamp': FieldValue.serverTimestamp()
});
} catch (e) {
print(e);
}
}
i solved my issue
Future<void> create(String todo, String description) async {
String? Uid= FirebaseAuth.instance.currentUser!.uid;
print(Uid);
print(FirebaseAuth.instance.currentUser!.uid);
try {
await firestore
.collection("TodoList")
.doc(Uid)
.collection("Todo")
.add({
'todo': todo,
'description': description,
'timestamp': FieldValue.serverTimestamp()
});
} catch (e) {
print(e);
}
}
Future<void> signUpController(email, password, username, phone) async {
print("$email,$password,$username,$phone");
try {
CommanDialog.showLoading();
final credential =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email.trim(),
password: password,
);
print(credential);
CommanDialog.hideLoading();
try {
CommanDialog.showLoading();
var response =
await FirebaseFirestore.instance.collection('userlist').add({
'user_id': credential.user!.uid,
'user_name': username,
'phone': phone,
'password': password,
'joindate': DateTime.now().millisecondsSinceEpoch,
'email': email
});
print("response:: ${response.toString()}");
CommanDialog.hideLoading();
Get.back();
} catch (execption) {
CommanDialog.hideLoading();
print("error saving data ${execption}");
}
Get.back();
} on FirebaseAuthException catch (e) {
CommanDialog.hideLoading();
if (e.code == 'weak-password') {
CommanDialog.showErrorDialog(
description: "The password provided is too weak.");
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
CommanDialog.showErrorDialog(
description: "The account already exists for that email.");
print('The account already exists for that email.');
}
} catch (e) {
CommanDialog.hideLoading();
CommanDialog.showErrorDialog(description: "something went wrong");
print(e);
}
}
I am trying to have access to notificationId once it gets created however the delete function deletes all the documents under this collection ('user-notifications').
Do you know what I need to change so I can remove only one document rather than all documents in this collection?
Future<String> likeAnnouncementNotification(String announcementId,
String imageUrl, String ownerUid, String uid, List liked) async {
String notificationid = const Uuid().v1();
String res = "Some error occurred";
try {
if (liked.contains(uid)) {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.where("uid", isEqualTo: FirebaseAuth.instance.currentUser?.uid)
.get()
.then((value) {
value.docs.forEach((document) {
document.reference.delete();
});
});
} else {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.doc(notificationid)
.set(
{
'imageUrl': imageUrl,
'announcementId': announcementId,
'notificationid': notificationid,
'timestamp': DateTime.now(),
'type': 0,
'uid': uid
},
);
}
res = 'success';
} catch (err) {
res = err.toString();
}
return res;
}
the only thing i see that you need to specify what notification document you went to delete add it like parameter when you call likeAnnouncementNotification function
Future<String> likeAnnouncementNotification(
String announcementId,
String imageUrl,
String ownerUid,
String uid,
List liked,
) async {
String notificationid = const Uuid().v1();
String res = "Some error occurred";
try {
if (liked.contains(uid)) {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.where("uid", isEqualTo: FirebaseAuth.instance.currentUser?.uid)
.get()
.then((value) {
value.docs.forEach((notification) {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.doc(notification.id) // this is the problem you need to specify what notification document you went to delete.
.delete();
});
});
} else {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.doc(notificationid)
.set(
{
'imageUrl': imageUrl,
'announcementId': announcementId,
'notificationid': notificationid,
'timestamp': DateTime.now(),
'type': 0,
'uid': uid
},
);
}
res = 'success';
} catch (err) {
res = err.toString();
}
return res;
}
(Flutter) User is always getting null and unable to create user in realtime database
Future validateform() async {
FormState? formState = _formKey.currentState;
if(formState!.validate()) {
formState.reset();
User? user = firebaseAuth.currentUser;
// String? useruid = user!.uid;
print(user);
if(user == null ) {
print(_emailTextController.text);
print(_nameTextController.text);
print('UserID: '+'{$user}');
print(gender);
firebaseAuth
.createUserWithEmailAndPassword(
email: _emailTextController.text,
password: _passwordTextController.text)
.then((user) => {
_userServices.createUser(
{
"username": _nameTextController.text,
"email": _emailTextController.text,
// "userId": useruid,
"userId": user.user!.uid,
// "userId": "5as564d65as4d65as4d65as4d64",
"gender": gender,
})
}).catchError((err) => {print(err.toString())});
// });
print(user);
if (user!=null) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
}
}
}
}
I was expecting it to creaete in REALTIME DATABASE as user details, but user is always null.
Trying to store image in books collection flutter but not letting me store and retrieve it later. Please help me trace the bug. Problem is with coverImage that is not letting me store the image URL in firebase so that the image could be displayed when its fetched later.
if (name != null &&
price != null &&
author != null &&
description != null &&
discountpercentage != null &&
rating != null) {
if (action == 'create') {
await books_collection.add({
"name": name,
"price": price,
"author": author,
"description": description,
"discountpercentage": discountpercentage,
"rating": rating,
"createdAt": Timestamp.now(),
"coverImage": Timestamp.now(),
// "url": uploadFilterImage()
});
}
if (action == 'update') {
// Update the product
await books_collection.doc(documentSnapshot!.id).update({
"name": name,
"price": price,
"author": author,
"description": description,
"discountpercentage": discountpercentage,
"rating": rating,
"createdAt": Timestamp.now(),
"coverImage": uploadFilterImage()
});
Future<String> uploadFilterImage() async {
String url = "";
final ImagePicker _picker = ImagePicker();
XFile? image = await _picker.pickImage(source: ImageSource.gallery);
Uint8List fileBytes = await image!.readAsBytes();
if (fileBytes != null) {
final _firebaseStorage = FirebaseStorage.instance;
var name = Timestamp.now().millisecondsSinceEpoch;
print("$name");
var snapshot = _firebaseStorage.ref().child('$name');
print("$name");
TaskSnapshot task = await snapshot.putData(
fileBytes,
SettableMetadata(contentType: 'image/jpeg'),
);
url = await task.ref.getDownloadURL();
if (url.isNotEmpty) {
Get.snackbar("successfull", "image uploaded");
}
}
return url;
}
You need to await the uploadFilterImage() call in order to process the async function and not return a Future, but return the final value instead. The same is true for both your create and update cases.
await books_collection.doc(documentSnapshot!.id).update({
"name": name,
"price": price,
"author": author,
"description": description,
"discountpercentage": discountpercentage,
"rating": rating,
"createdAt": Timestamp.now(),
"coverImage": await uploadFilterImage() // here
});
i want to get the image link in database, but i get the image url in other document and (name & etc) in other document.
database.collection("car").add({
"item Name": nameText.text,
"item Price": priceText.text,
"seller Number": cellNoText.text,
"seller add": addText.text,
"image 1 Url": await uploadPic()
.then((value) async {
DocumentReference docRef = Firestore
.instance
.collection("car")
.document();
await docRef.setData(
{"image 1 Url": value},
merge: true);
}),
});
this is the function to upload the image to firebase storage
uploadPic() async {
String fileName = path.basename(_image1.path);
StorageReference reference = storage.ref().child(fileName);
StorageUploadTask uploadTask = reference.putFile(_image1);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String url = await taskSnapshot.ref.getDownloadURL();
imageUrl1 = url;
return url;
}
can you guys help?
Your image url has been created in the wrong location because of the then of the uploadPic(), and its null in the car document because you need to call the Future function before adding it to the document:
Future uploadPic() async {
String fileName = path.basename(_image1.path);
StorageReference reference = storage.ref().child(fileName);
StorageUploadTask uploadTask = reference.putFile(_image1);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String url = await taskSnapshot.ref.getDownloadURL();
return url;
}
Future saveData() async {
String imageUrl = await uploadPic(); //calling and adding the result to a variable before adding
database.collection("car").add({
"item Name": nameText.text,
"item Price": priceText.text,
"seller Number": cellNoText.text,
"seller add": addText.text,
"imageUrl": imageUrl,
});
}