My application has a function that allows to upload videos and other large files to Amazon S3 buckets via Amplify storage. The below function works as expected and uploads a file to my S3 bucket:
Future<String> uploadFile({File? file, String path = "", String fileName = "", String fileExtension = ""}) async {
try {
final key = path+fileName+'.'+fileExtension;
final result = await Amplify.Storage.uploadFile(
local: file!,
key: key,
);
return result.key;
} catch (e) {
throw e;
} }
However, given the size of some of these files, the time required to upload can be large and I want to avoid that my users have to wait until the file is completely uploaded. Therefore I want to run the above function in a dart Isolate
, so that the file can continue uploading while my user Navigates to different screens of the app.
I tried to achieve this with the below function:
static uploadFileIsolate(List<dynamic> args) async {
try {
SendPort responsePort = args[0];
File file = args[1];
String path = args[2];
String fileName = args[3];
String fileExtension = args[4];
final key = path+fileName+'.'+fileExtension;
final result = await Amplify.Storage.uploadFile(
local: file,
key: key,
);
Isolate.exit(responsePort, result);
} catch (e) {
throw e;
} }
Which I call like this from my main function:
final p = ReceivePort();
Isolate.spawn(uploadFileIsolate, [p.sendPort, file, path, fileName, fileExtension]);
This is not working and throws the below error:
[VERBOSE-2:dart_isolate.cc(1111)] Unhandled exception:
RangeError (index): Invalid value: Valid value range is empty: 0
#0 DatabaseService.uploadFileIsolate (package:mastory/services/database_service.dart:202:7)
#1 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:300:17)
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
After reading this issue it makes me think that the error comes from the fact that Amplify is not configured in the 'isolated' environment.
So my question is: How can I make Amplify's uploadFile function work in an Isolate?
Or, if that is not possible, how can I make sure that the uploadFile function continues until completion while allowing my user to Navigate to other screens in my app?