First this is about my uploadImage code, I try to fix it again and again but doesn't work
Future uploadImageFile() async
{
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
StorageReference storageReference = FirebaseStorage.instance.ref().child("Chat Images").child(fileName);
StorageUploadTask storageUploadTask = storageReference.putFile(imageFile);
StorageTaskSnapshot storageTaskSnapshot = await storageUploadTask.onComplete;
storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl){
imageUrl = downloadUrl;
setState(() {
isLoading = false;
onSendMessage(imageUrl, 1);
});
}, one rror: (error){
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: "Error: " error);
});
}
And after in click upload image the result in terminal like this :
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type 'PlatformException' is not a subtype of type 'String'
#0 ChatScreenState.uploadImageFile.<anonymous closure> (package:telegramchatapp/Pages/ChattingPage.dart:726:47)
#1 _rootRunUnary (dart:async/zone.dart:1436:47)
#2 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
#3 _FutureListener.handleError (dart:async/future_impl.dart:178:22)
#4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:779:47)
#5 Future._propagateToListeners (dart:async/future_impl.dart:800:13)
#6 Future._completeError (dart:async/future_impl.dart:610:5)
#7 _completeOnAsyncError (dart:async-patch/async_patch.dart:276:13)
#8 StorageReference.getDownloadURL (package:firebase_storage/src/storage_reference.dart)
<asynchronous suspension>
I don't know what to do.
CodePudding user response:
I made a simple function to upload to Firebase Storage that works for me:
storage.dart
Future upload({required String ref, required File file}) async {
return await FirebaseStorage.instance.ref(ref).putFile(file).catchError(
(e) => Utils.log(
e,
type: LogType.error,
),
);
}
Future<String> downloadURL({required String ref}) async {
return await FirebaseStorage.instance.ref(ref).getDownloadURL().catchError(
(e) => Utils.log(
e,
type: LogType.error,
),
);
}
This Utils.log()
is just a logger, you can use Toast if you want. And this is how I use it:
anywhere_else.dart:
String ref = 'users/${Services.auth.currentUser()!.uid}/selfie.png';
var upload = await Services.storage.upload(ref: ref, file: selfie);
if (upload != null) {
user.selfie = await Services.storage.downloadURL(ref: ref);
}
CodePudding user response:
The exception you show in your question comes from this line:
Fluttertoast.showToast(msg: "Error: " error);
The error
in here is not a string, so you can't concatenate it to a string. What you want is:
Fluttertoast.showToast(msg: "Error: " error.toString());
Or:
Fluttertoast.showToast(msg: "Error: $error");
That will then show you what the root cause of the upload failure is, so you can address that.