Flutter Web Firebase storage error response storage/unkown - firebase

hope all is well.
I have been trying to upload an image or file to firebase storage from flutter web. Once I try to call put data the console just reads
Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)
I don't know how to check server response when using a plugin but this error comes from the try-catch block with on firebaseexception print error
Code: XFile? pickedImage;
_startFilePicker() async {
pickedImage = await ImagePicker().pickImage(
source: ImageSource.camera,
imageQuality: 60,
maxWidth: 250,
);
setState(() {
_hasUploaded = true;
});
uploadImageToStorage(pickedImage);
}
String uploadedPhotoUrl = '';
uploadImageToStorage(XFile? pickedFile) async {
try {
final String url = FirebaseStorage.instance.bucket;
Reference _reference = FirebaseStorage.instance
.refFromURL(
'gs://genderbasedviolence-bd860.appspot.com/') //${FirebaseAuth.instance.currentUser!.uid}
.child('images');
final bytes = await pickedFile!.readAsBytes();
await _reference.putData(bytes);
} on FirebaseException catch (e) {
print(e.code);
}
}
Please let me know if you need more info. Thanks

Related

Flutter Firebase Storage Unable to upload File

I am trying to upload a image using the code below:
Future<String> uploadImageToFirebase(File imageFile) async {
String fileName = basename(imageFile.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(imageFile);
var taskSnapshot = await uploadTask;
String imageUrl = "";
await taskSnapshot.ref.getDownloadURL().then(
(value) {
// print("Upload Image Completed: $value");
imageUrl = value;
},
);
return imageUrl;
}
But I get the following error:
E/StorageException(15399): Caused by: java.io.IOException: { "error": { "code": 400, "message": "Your bucket has not been set up properly for Firebase Storage. Please visit 'https://console.firebase.google.com/project/imgs-e4332/storage/files' to automatically repair this issue and then retry. If the issue lasts longer than five minutes, you may have insufficient permissions to repair the project. You can check your permissions by visiting 'https://console.firebase.google.com/iam-admin/iam/project?project=imgs-e4332'." }}

Flutter Firestore Storage get downloadUrl

I need to get the downloadURL from uplaoding a photo to a Firebase Storage so I can store it inside of a Firestore document. The issue with my code is that the URL that is saved isnt a https//: so I need to get the downloadURL. I was wondering where I need to call it to get the downloadUrl and save it inside of my Firestore Database.
Here is my code:
Future<void> _uploadProfilePhoto(String inputSource) async {
final picker = ImagePicker();
PickedFile? pickedImage;
try {
pickedImage = await picker.getImage(
source: inputSource == 'camera'
? ImageSource.camera
: ImageSource.gallery,
maxWidth: 1920);
final String fileName = path.basename(pickedImage!.path);
File imageFile = File(pickedImage.path);
try {
await storage.ref("avatars/$fileName").putFile(
imageFile,
SettableMetadata(customMetadata: {
'uploaded_by': '$uid',
}));
// Create/Update firesotre document
users.doc(uid).update({
"profilePhoto": fileName,
});
setState(() {});
} on FirebaseException catch (error) {
print(error);
}
} catch (err) {
print(err);
}
}
You can call getDownloadURL() on the reference at any time after the file upload has completed. So this would be a good spot:
await storage.ref("avatars/$fileName").putFile(
imageFile,
SettableMetadata(customMetadata: {
'uploaded_by': '$uid',
}));
var downloadURL = await storage.ref("avatars/$fileName").getDownloadURL();
// Create/Update firesotre document
users.doc(uid).update({
"profilePhoto": downloadURL,
});

Unable to use a Callable Cloud Function in Flutter

I'm currently using a Firebase Cloud Function, which I wish I can use on Call to check if an Image has adult content, and see some of the tutorials out there I manage to create this function:
exports.checkImage = functions.https.onCall(async (data, context) => {
const img_base64 = data;
const request = {
image: {
content: img_base64
}
};
try {
const [result] = await client2.safeSearchDetection(request);
console.log(result.safeSearchAnnotation?.adult);
return result.safeSearchAnnotation?.adult;
} catch (error) {
console.log(error);
return;
}
return;
});
Now I'm tried to send the Image using an iOS Emulator with that call Function in 2 ways:
First Option I tried:
1.
exports.checkImage = functions.https.onCall(async (data, context) => {
const img_base64 = data;
const request = {
image: {
content: img_base64
}
};
try {
const [result] = await client2.safeSearchDetection(request);
console.log(result.safeSearchAnnotation?.adult);
return result.safeSearchAnnotation?.adult;
} catch (error) {
console.log(error);
return;
}
return;
});
The problem here is I get this Error on my Debugging Console:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method FirebaseFunctions#call on channel plugins.flutter.io/firebase_functions)
#0 convertPlatformException (package:cloud_functions_platform_interface/src/method_channel/utils/exception.dart:16:5)
#1 MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:39:13)
<asynchronous suspension>
#2 HttpsCallable.call (package:cloud_functions/src/https_callable.dart:35:37)
<asynchronous suspension>
#3 DatabaseMethods.clearImage
package:property1/providers/database.dart:294
In someplace I read that the onCall Cloud Functions can be use as regular End Points so I did this:
clearImage(imageX) async {
final url = Uri.parse(
'https://us-central1-XXXXXXX-XXXX.cloudfunctions.net/checkImage',
);
try {
final response = await http.post(
url,
body: json.encode({
"image": {
"content": imageX
}),
);
}
}
In this one, I only get an Invalid Request unable to process.
I even try this from Postman getting the same result bad request.
As additional data I call this function from where I select the Image with this code:
void _pickImage() async {
final imagePicker = ImagePicker();
final pickedImageFile = await imagePicker.getImage(
source: ImageSource.gallery,
imageQuality: 50,
);
setState(() {
if (pickedImageFile != null) {
_pickedImage = File(pickedImageFile.path);
}
});
// This section will be used to check the Images with Google Vision.
List<int> imageBytes = _pickedImage.readAsBytesSync();
String base64Image = base64Encode(imageBytes);
DatabaseMethods().clearImage(base64Image);
widget.imagePickFn(File(pickedImageFile.path));
}
Basically, I convert the image to a Base64 encoded image that I send so Cloud Vision could work with it.
I even try to just check if I get to the Cloud Function by Commenting out the try of Cloudvision and just adding a console log to get what data is receiving but it is never reached, always an Invalid request, unable to process is what I get.
Any ideas on why I'm not reaching the Function, or on how I can test this from my iOS Emulator.
Kind Regards,
For calling onCall cloud functions from flutter apps, you have to use FirebaseFunctions.instance.httpsCallable():
import 'package:cloud_functions/cloud_functions.dart';
try {
final result =
await FirebaseFunctions.instance.httpsCallable('checkImage').call();
} on FirebaseFunctionsException catch (error) {
print(error.code);
print(error.details);
print(error.message);
}
First, install the package:
flutter pub add cloud_functions
Here's the documentation.

Uncaught Reference error: Toastify is not defined flutter web

I am new to flutter web. I have implemented firebase login functionality in my flutter web application. This functionality works correctly in local. But When i deploy the website on my own server, if i enter correct credentials, it works correctly on live, but whenever i enter wrong password, at that time it gives me exception,
Uncaught ReferenceError: Toastify is not defined
I have used fluttertoast library to dispaly toast messages, i m not sure what is causing the issue, is this error related to toast message or related to firebase. Please see attached screenshot of error
Is this issue related to fluttertoast library or related to firebase? How to resolve this issue, do we need to do any configuration related to domain in firebase?
I am using following code to signin User
Future<void> _signInWithEmailPassword() async {
UtilityHelper.showToast(message: "Login clicked");
_formkey.currentState?.save();
bool _isValid = _formkey.currentState?.validate() ?? false;
FocusScope.of(context).requestFocus(FocusNode());
if (_isValid) {
setState(() {
_loginType = LoginType.normal;
_isLoading = true;
});
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final hasResponse = await authProvider.singInUser(loginReqModel);
redirectToHome(hasResponse, authProvider);
}
}
late UserModel _user;
UserModel get user => _user;
bool get isChangePasswordButtonShown =>
_authRepo.isUserLoggedInUsingPasssword;
String errorMsg = '';
Future<bool> singInUser(LoginReqModel reqModel) async {
try {
final response = await _authRepo.singInUser(reqModel);
if (response != null) {
_user = response;
notifyListeners();
return true;
}
notifyListeners();
return false;
} catch (error) {
print(error);
errorMsg = UtilityHelper.getErrorMessage(error);
return false;
}
}
Any help would be appreciated.
This issue was related to flutter toast library that i was using to display toast message, it did not worked with live domain.
So replacing that library with oktoast library solved the issue

Flutter Firebase Storage 0.5.0 upload file and video error

What I want to do: Upload a file and a video with Firebase Storage 0.5.0 and return url.
What current problem is: I can upload file and image with Firebase storage 0.5.0, but I can't return url. I also see my file and video uploaded in Firebase storage in Firebase console.
My code:
Future<String> _uploadFile(Reference ref, File file,
[SettableMetadata metadata]) async {
UploadTask uploadTask = ref.putFile(file, metadata);
uploadTask.whenComplete(() async {
try {} catch (onError) {
print("Error");
}
});
final url = await ref.getDownloadURL();
return url;
}
Future<String> uploadVideo(File video,
{String refName, SettableMetadata metadata}) async {
metadata = SettableMetadata(contentType: 'video/mp4');
final name = refName != null ? refName : path.basename(video.path);
final ref = _VideoRef.child(name);
return _uploadFile(ref, video, metadata);
}
Future<File> downloadImage(String imageUrl, String savePath) async {
final ref = _storage.ref(imageUrl);
var file = File(savePath);
await ref.writeToFile(file);
return file;
}
What the console told me:
FirebaseException (Firebase_storage/object-not-found). No object exist in desired reference.
How do I fix this?
Try the following:
uploadTask.whenComplete(() async {
try {
url = await ref.getDownloadURL();
} catch (onError) {
print("Error");
}
});
When the future completes, call getDownloadURL() to get the url.

Resources