Flutter Image Compress giving result as null - firebase

Compressed is coming out as null
File compressed = await FlutterImageCompress.compressAndGetFile(
img.path,
img.path.split('/').last,
quality: 80,
);
ref = firebase_storage.FirebaseStorage.instance
.ref()
.child('postimages/${Path.basename(img.path)}');
await ref.putFile(compressed);
This is what the error I am getting
E/flutter (12851): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception:
NoSuchMethodError: The getter 'absolute' was called on null.
E/flutter (12851): Receiver: null
E/flutter (12851): Tried calling: absolute
E/flutter (12851): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (12851): #1 Reference.putFile
package:firebase_storage/src/reference.dart:126
E/flutter (12851): #2 _AddImageState.uploadFile
package:softclaw/…/addpost/addimage.dart:228
E/flutter (12851):
E/flutter (12851):

This will work perfectly fine
final imageUri = Uri.parse(img.path);
final String outputUri = imageUri.resolve('./output.webp').toString();
print(imageUri.toFilePath());
File compressed = await FlutterImageCompress.compressAndGetFile(
img.path, outputUri,
quality: 80, format: CompressFormat.webp);
print(img.path);
print(outputUri);
ref = firebase_storage.FirebaseStorage.instance
.ref()
.child('postimages/${Path.basename(img.path)}');
await ref.putFile(compressed);
_imageName.add(await ref.getDownloadURL());
}

Related

Dart Unhandled Exception: [firebase_storage/unknown] location should not be a full URL

I tried to use the plugin https://pub.dev/packages/flutter_cache_manager_firebase to cache my audio that saved in firebase storage with the url of
https://firebasestorage.googleapis.com/v0/b/ocwa-app.appspot.com/o/142-1624205564448.aac?alt=media&token=b06a7cf9-5050-43ad-b5e9-60c4eda85b54
When I pass the url to the method
file = await FirebaseCacheManager().getSingleFile(widget.url);
and it throws an error in console
E/flutter (32343): [ERROR:flutter/shell/common/shell.cc(103)] Dart Unhandled Exception: [firebase_storage/unknown] location should not be a full URL., stack trace: #0 MethodChannelReference.getDownloadURL (package:firebase_storage_platform_interface/src/method_channel/method_channel_reference.dart:59:7)
E/flutter (32343): <asynchronous suspension>
E/flutter (32343): #1 FirebaseHttpFileService.get (package:flutter_cache_manager_firebase/src/firebase_http_file_service.dart:12:16)
E/flutter (32343): <asynchronous suspension>
E/flutter (32343): #2 WebHelper._updateFile (package:flutter_cache_manager/src/web/web_helper.dart:99:22)
E/flutter (32343): <asynchronous suspension>
E/flutter (32343): #3 WebHelper._downloadOrAddToQueue (package:flutter_cache_manager/src/web/web_helper.dart:67:7)
E/flutter (32343): <asynchronous suspension>
Please show me how to pass the correct url to the parameter. The current url I used is the downloadUrl return from
Future uploadAudio() async {
final uploadTimestamp = DateTime.now().millisecondsSinceEpoch;
setState(() {
fileName =
getImageFileName(G.loggedInId.toString(), '$uploadTimestamp');
fileName = fileName + '.aac';
});
Reference reference = FirebaseStorage.instance.ref().child(fileName);
TaskSnapshot uploading;
uploading = await reference.putFile(
File(recordingFile), SettableMetadata(contentType: 'audio/aac'));
return uploading.ref.getDownloadURL();
}
You need to remove the scheme from the URL.
You can do this like this:
final String url = widget.url;
final Uri uri = Uri.parse(url);
final urlWithoutScheme = url.replaceFirst('${uri.scheme}://', '');
///Pass it to the getSingleFile method
file = await FirebaseCacheManager().getSingleFile(urlWithoutScheme);
The code below is where the error is thrown from https://github.com/firebase/firebase-android-sdk/blob/master/firebase-storage/src/main/java/com/google/firebase/storage/FirebaseStorage.java.
if (lowerCaseLocation.startsWith("gs://")
|| lowerCaseLocation.startsWith("https://")
|| lowerCaseLocation.startsWith("http://")) {
throw new IllegalArgumentException("location should not be a full URL.");

NoSuchMethodError: The method 'ref' was called on null

there I want help, I was creating my app with flutter and firebase,
there, I want to upload images to firebase storage.
so my file
import 'package:firebase_storage/firebase_storage.dart';
uploadTOFirebase() async {
final ref = FirebaseStorage.instance.ref('posts/post_$postId.jpg');
await ref.putFile(image).whenComplete(() async {
final url = await ref.getDownloadURL();
setState(() {
postlink = url;
});
// print(postlink);
});
}
but that saw me that error
E/flutter (19469): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'ref' was called on null.
E/flutter (19469): Receiver: null
E/flutter (19469): Tried calling: ref("posts/post_27cfad88-62bb-4211-9e5b-0c6d1e9029be.jpg")
E/flutter (19469): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (19469): #1 _UploadState.uploadTOFirebase (package:instaclone/pages/upload.dart:230:48)
E/flutter (19469): #2 _UploadState.HandleSubmit (package:instaclone/pages/upload.dart:226:11)
E/flutter (19469): <asynchronous suspension>
E/flutter (19469):
and I'm using flutter in andoird
Try using it like this.
final ref = FirebaseStorage.instance.ref().child("posts/post_$postId.jpg");
Did you call Firebase.initializeApp() anywhere? Without that, the Firebase SDKs won't be able to find your project on Google's servers.
See initializing FlutterFire in the FlutterFire docs for an example of how to do this.
uploadTOFirebase() async {
UploadTask storageUploadTask = FirebaseStorage.instance.putFile('posts/post_$postId.jpg');
TaskSnapshot storageTaskSnapshot =
await storageUploadTask.whenComplete(() => null);
String url = await storageTaskSnapshot.ref.getDownloadURL();
setState((){postlink = url;});
}
Try this code. Did some small changes.

Flutter firebase function error : Response is not valid JSON object

Hello I tried to use firebase function by using Cloud_Functions Pkg but I got error in flutter consel , I tried to pass parameters in function which is UID of user .
Consel Error :
E/flutter (17871): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: [firebase_functions/internal] Response is not valid JSON object.
E/flutter (17871): #0 catchPlatformException
package:cloud_functions_platform_interface/…/utils/exception.dart:21
E/flutter (17871): #1 _rootRunBinary (dart:async/zone.dart:1378:47)
E/flutter (17871): #2 _CustomZone.runBinary (dart:async/zone.dart:1272:19)
E/flutter (17871): #3 _FutureListener.handleError (dart:async/future_impl.dart:166:20)
E/flutter (17871): #4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:716:47)
E/flutter (17871): #5 Future._propagateToListeners (dart:async/future_impl.dart:737:24)
E/flutter (17871): #6 Future._completeError (dart:async/future_impl.dart:547:5)
E/flutter (17871): #7 _completeOnAsyncError (dart:async-patch/async_patch.dart:264:13)
E/flutter (17871): #8 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart)
package:flutter/…/services/platform_channel.dart:1
E/flutter (17871): <asynchronous suspension>
Firebse Function :
exports.helloWorld = functions.https.onCall((data, context) => {
return data.data()['uid'];
});
Flutter run function from Firebase :
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
HttpsCallable callable =
FirebaseFunctions.instance.httpsCallable('listFruit');
final results = await callable.call(<String, dynamic>{
'uid': '123',
});
print(results
.data.toString()); // ["Apple", "Banana", "Cherry", "Date", "Fig", "Grapes"]
});
My goal :
pass parameters to firebase function .
I had the same error and it was due to the fact that the region was not provided, which seems to be required if the function is not deployed in us-central1. Following their documentation, you can perform the call like this:
FirebaseFunctions.instanceFor(region: 'europe-west1').httpsCallable('listFruit');
Instead of
exports.helloWorld = functions.https.onCall((data, context) => {
return data.data()['uid'];
});
you should do
exports.helloWorld = functions.https.onCall((data, context) => {
return data['uid']; // Or data.uid
});
Few more details in the Callable Cloud Functions doc.
In addition, note that your Cloud Function is named helloWorld but you call it with FirebaseFunctions.instance.httpsCallable('listFruit');. So you should adapt one or the other, e.g. FirebaseFunctions.instance.httpsCallable('helloWorld');

How to save multiple images to firebase storage and get image urls at once?

I'm trying to save multiple images from a list to firebasestorage and get back references of all these images and then saving it to cloud firestore !
This list is List<menu> menus = []; here.
Multiple objects including paths of images only from phone are being saved from UI in this list(menus) and then I'm uploading images using these paths to firestorage and getting back its references to save it in firestore:
onPressed: () async {
for (var i; i <= menus.length; i++) {
Reference ref = storage.ref().child(
"${this.widget.rr.name}'s ${menus[i].itemName} Price ${menus[i].itemPrice}" +
DateTime.now().toString());
if (menus[i].imageFile.toString() == '') {
//Some code
} else {
UploadTask uploadTask = ref.putFile(menus[i].imageFile);
uploadTask.then((res) async {
menus[i].imageUrl = await res.ref.getDownloadURL();
});
}
}
await addUser();
},
This is addUser() function:
Future<void> addUser() {
return users
.add({
'name': this.widget.rr.name,
'email': this.widget.rr.email,
'password': this.widget.rr.password,
'logoUrl': this.widget.rr.logo,
'categories': this.widget.rr.categories,
'menu': menus.map((i) => i.toMap()).toList(),
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
}
And this is Model class
class menu{
int id;
String itemName;
String itemPrice;
String itemDescription;
File imageFile;
String imageUrl;
menu(this.id,this.itemName,this.itemPrice,this.itemDescription,this.imageFile,{this.imageUrl});
Map<String, dynamic> toMap() {
return {
'id': this.id,
'itemName': this.itemName,
'itemPrice': this.itemPrice,
'itemDesc': this.itemDescription,
'imageUrl':this.imageUrl,
};
}
}
But when the button is pressed, following error is displayed...
E/flutter (12025): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '<=' was called on null.
E/flutter (12025): Receiver: null
E/flutter (12025): Tried calling: <=(2)
E/flutter (12025): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (12025): #1 _addMenuState.build.<anonymous closure> (package:ad_tello/UI/Restaurants/addMenu.dart:418:33)
E/flutter (12025): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
E/flutter (12025): #3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
E/flutter (12025): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
E/flutter (12025): #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
E/flutter (12025): #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
E/flutter (12025): #7 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:259:7)
E/flutter (12025): #8 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
E/flutter (12025): #9 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:362:20)
E/flutter (12025): #10 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
E/flutter (12025): #11 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
E/flutter (12025): #12 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
E/flutter (12025): #13 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
E/flutter (12025): #14 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
E/flutter (12025): #15 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (12025): #16 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (12025): #17 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (12025): #18 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter (12025): #19 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
E/flutter (12025):
Help please!
You have to initialize i:
for (var i = 0; i < menus.length; i++) {

I was trying to upload video on firebase but it gives me an error

The method 'existsSync' was called on null.
Receiver: null
Tried calling: existsSync()
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 StorageReference.putFile (package:firebase_storage/src/storage_reference.dart:62:17)
#2 _UploadState.uploadImage (package:focal/pages/upload.dart:402:10)
#3 _UploadState.handleVideoSubmit (package:focal/pages/upload.dart:507:30)
<asynchronous suspension>
#4 _UploadState.buildUploadForm.<anonymous closure> (package:focal/pages/upload.dart:613:27)
#5 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
#6 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
#7 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
#8 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
#9 BaseTapGestureRecognizer._chec<…>
What does this error means
I was just uploading a video file and it gives me this error.
This is my code below for uploading video
final StorageReference storageRef = FirebaseStorage.instance.ref();
Future<String> uploadVideo(videoFile, String postId) async {
StorageUploadTask uploadTask = storageRef
.child(
'post_/$postId/${widget.currentuser.username}',
)
.putFile(videoFile);
String thumbnail = 'post_/$postId/${widget.currentuser.username}';
setState(() {
thumbnailLocation = thumbnail;
});
StorageTaskSnapshot storageSnap = await uploadTask.onComplete;
String downloadUrl = await storageSnap.ref.getDownloadURL();
return downloadUrl;
}
Check that you have initialized storageRef

Resources