Firebase Storage await uploadTask.onComplete outdated - firebase

Im using this code.
The error message is the following:
error: The getter 'onComplete' isn't defined for the type 'UploadTask'. (undefined_getter at [chatneu] lib/Screens/HomeScreen.dart:289)
Future uploadFile() async {
try {
pr = new ProgressDialog(context);
await ImagePicker().getImage(
source: ImageSource.gallery).then((image) {
setState(() {
_image = image as File;
//klammern weg bei ImagePicker und .getImage zu Pickimage
});
});
await pr.show();
Reference storageReference = FirebaseStorage.instance.ref().child(
'${loggedInUser.uid}/UserProfille/${Path.basename(_image.path)}');
UploadTask uploadTask = storageReference.putFile(_image);
await uploadTask.onComplete;
print('File Uploaded');
storageReference.getDownloadURL().then((fileURL) {
setState(() {
FirebaseFirestore.instance.collection('Users').doc(loggedInUser.uid);
Map<String, String> data = {
'photoUrl': fileURL,
};

I'm not sure where you got the idea that there is a method called onComplete on the UploadTask. If you follow the example code in the documentation, you will see that you just await the UploadTask directly:
await storageReference.putFile(_image);
storageReference.getDownloadURL().then(...);
You might also want to review the docs on handling tasks.

onComplete does not have any more but there is different method is whenComplete may replace what you need.
await ref.putFile(image).whenComplete(() => doSomething());

Related

How to get the url from Firebase Storage file?

I want to retrieve the URL of a Uint8List image from firebase storage. But I am not able to do that. It prints a snapshot, not the url. Please help.
my code:
void _storeSignature() async {
try {
final Uint8List? signature = await exportSignature();
final FirebaseStorage? storage = FirebaseStorage.instance;
final String? pictureUrl =
"signature/${DateTime.now().millisecondsSinceEpoch.toString()}.png";
final ref = storage!.ref().child(pictureUrl!);
final uploadTask = ref.putData(signature!);
final downurl = await uploadTask.whenComplete(() {
return ref.getDownloadURL();
});
final url = downurl.toString();
print(url);
} catch (e) {
rethrow;
}
}
You have to await for the URL when calling ref.getDownloadURL()
change
return ref.getDownloadURL();
into
return await ref.getDownloadURL();
The UploadTask class extends Future, so you can also use await there already:
await ref.putData(signature!);
final downurl = await ref.getDownloadURL();
final url = downurl.toString();

What is the the method to use onComplete function to add Images to Firebase Storage

I have made a function to upload three images to firebase storage. I have been doing it with the help of a tutorial. Since the tutorial uses old version codes I am trying my maximum to change it to a newer version. In the tutorial, it uses onComplete method to get the task snapshot. But in the pub.dev docs it is said that these methods have been removed and their is an exception Like this(
BREAKING: isCanceled, isComplete, isInProgress, isPaused and isSuccessful have now been removed. Instead, you should subscribe to the stream (for paused/progress/complete/error events) or the task Future for task completion/errors.)
please tell what does this mean and how can I change my below code according to it.
there is an error showing in the place where I type onComplete
void validateAndUpload() async{
if (_formKey.currentState.validate()) {
if (_image1 != null && _image2 != null && _image3 != null) {
if (selectedSizes.isNotEmpty) {
String imageUrl1;
String imageUrl2;
String imageUrl3;
final FirebaseStorage storage = FirebaseStorage.instance;
final String picture1 =
'1${DateTime.now().millisecondsSinceEpoch.toString()}.jpg';
UploadTask task1 = storage.ref().child(picture1).putFile(_image1);
final String picture2 =
'2${DateTime.now().millisecondsSinceEpoch.toString()}.jpg';
UploadTask task2 = storage.ref().child(picture2).putFile(_image2);
final String picture3 =
'3${DateTime.now().millisecondsSinceEpoch.toString()}.jpg';
UploadTask task3 = storage.ref().child(picture3).putFile(_image3);
TaskSnapshot snapshot1 = await task1.onComplete.then((snapshot) => snapshot);
TaskSnapshot snapshot2 = await task1.onComplete.then((snapshot) => snapshot);
task3.onComplete.then((snapshot3) async{
imageUrl1 = await snapshot1.ref.getDownloadURL();
imageUrl2 = await snapshot2.ref.getDownloadURL();
imageUrl3 = await snapshot3.ref.getDownloadURL();
});
} else {
Fluttertoast.showToast(
msg: "Sizes cannot be Empty",
backgroundColor: Colors.red,
textColor: Colors.white);
}
} else {
Fluttertoast.showToast(
msg: "Images are not Filled",
backgroundColor: Colors.red,
textColor: Colors.white);
}
}
}
You are almost there! As the error says either you have to listen for the UploadTask streams or await for UploadTask to complete. For your case,
TaskSnapshot snapshot1 = await task1;
TaskSnapshot snapshot2 = await task2;
TaskSnapshot snapshot3 = await task3;
imageUrl1 = await snapshot1.ref.getDownloadURL();
imageUrl2 = await snapshot2.ref.getDownloadURL();
imageUrl3 = await snapshot3.ref.getDownloadURL();
For more ref - https://firebase.flutter.dev/docs/storage/usage/#handling-tasks

How to upload pdf to firebase storage with flutter?

I'm using latest firebase_storage version now some methods and references of storage are updated ploadTask.onComplete does not support.
so how do I get uploaded pdf url?
Piece of code:
Future<String> uploadPdfToStorage(File pdfFile) async {
try {
Reference ref = FirebaseStorage.instance.ref().child('pdfs/${DateTime.now().millisecondsSinceEpoch}');
UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'pdf'));
String downloadUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
final String url = await downloadUrl;
print("url:$url");
return url;
} catch (e) {
return null;
}
}
Here's an edited code that should work with the latest firebase storage_package:
Future<String> uploadPdfToStorage(File pdfFile) async {
try {
Reference ref =
FirebaseStorage.instance.ref().child('pdfs/${DateTime.now().millisecondsSinceEpoch}');
UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'pdf'));
TaskSnapshot snapshot = await uploadTask;
String url = await snapshot.ref.getDownloadURL();
print("url:$url");
return url;
} catch (e) {
return null;
}
}

Flutter get data from firebase correctly

Hey In my app you can edit your profile for example select a picture from your gallery for your profile picture. All work fine when I'm in the app. But when I close the app and open it again the profile picture is gone. When I select a picture from the gallery the url is stored in cloud firebase. In my code I retrieve the url from cloud firebase and want that this Constants.URL_Profil_Picture = value.docs[0].data()['url']; is work. But it doesnt work. Does anyone know why?
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
getData() async {
return await _fireStore.collection("SerX").get();
}
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(
fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
_URL = downUrl.toString();
setState(() async {
print('Profile Picture uploaded');
var firebaseUser = await FirebaseAuth.instance.currentUser;
FirebaseFirestore.instance.collection("SerX").doc(firebaseUser.uid).update({"url" : downUrl});
getData().then((value){
if(value.docs.length > 0){
Constants.URL_Profil_Picture = value.docs[0].data()['url'];
print(value.docs[0].data()['url']);
}
});
print(Constants.URL_Profil_Picture);
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Profile Picture Uploaded')));
});
}

How to Load Image to Firebase Storage and get downloadUrl (Flutter/Firebase)

I want to implement sending files to Firebase Storage, as well as get a link to it. But for some reason it does not work ...
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
var fileUrl = ref.putFile(file).onComplete.then((file) =>
file.ref.getDownloadURL());
print(fileUrl);
_sendMessage(fileUrl: fileUrl.toString());
}
...
prefixIcon: IconButton(
icon: Icon(Icons.attach_file),
color: Colors.white,
onPressed: () => _pickFile()
)
Why do I get this instead of a link?
I/flutter (16610): Instance of 'Future'
I need a link in the String!
What is the problem?
Like the log say, fileUrl is a Future who is not resolved yet. You should make sure it's resolve to make use of the string give.
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
String fileUrl = await (await ref.putFile(file).onComplete).ref.getDownloadURL();
print(fileUrl);
_sendMessage(fileUrl: fileUrl.toString());
}
You need use await for Future functions
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
final StorageUploadTask uploadTask = ref.putFile(file);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
_sendMessage(fileUrl: downloadUrl);
}
It would look like this without using await
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
ref.putFile(file).onComplete.then((file){
var fileUrl = file.ref.getDownloadURL());
_sendMessage(fileUrl: fileUrl.toString());
});
}
here is my solution to upload and get the uploaded image url
first i get image with image picker
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
});
}
then i upload to firebase
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');
setState(() {
print("Profile Picture uploaded");
print("....................$url");
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Profile Picture Uploaded')));
});
}
this is the part i get the downloadUrl of currently uploaded image
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');

Resources