How can I upload PDF file in firebase storage and generate download URL and save firebase using Flutter?
You're getting the error because the fileBytes
variable was null at runtime and you're using the null check operator on it.
The reason for the null bytes from the picked file is because by default, the byte data is not returned from the pickFiles method (except for web). You need to set withData
to true
and the null error should disappear.
If withData is set, picked files will have its byte data immediately available on memory as Uint8List which can be useful if you are picking it for server upload or similar. However, have in mind that enabling this on IO (iOS & Android) may result in out of memory issues if you allow multiple picks or pick huge files. Use withReadStream instead. Defaults to true on web, false otherwise.
Update your code to this:
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
withData: true
);
Mostafijur Rahman
Updated on January 01, 2023Comments
-
Mostafijur Rahman over 1 year
I tried below the code but getting issues:
Unhandled Exception: Null check operator used on a null value
FirebaseStorage storage = FirebaseStorage.instance; FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['pdf'], withData: true ); if (result != null) { Uint8List? fileBytes = result.files.first.bytes; String fileName = result.files.first.name; // Upload PDF file TaskSnapshot taskSnapshot = await storage.ref('CV/$fileName').putData(fileBytes!); String pdfUrl = await taskSnapshot.ref.getDownloadURL(); print('pdf url: $pdfUrl'); }
-
Mostafijur Rahman over 2 yearsThanks a lot, it's working. For generating PDF download URL: TaskSnapshot taskSnapshot = await storage.ref('CV/$fileName').putData(fileBytes!); String pdfUrl = await taskSnapshot.ref.getDownloadURL();