Upload in background on Flutter

Viewed 833

What’s the best way to upload data in the background, but don’t cancel this upload when the user switches screens? I would also like to show Snackbar when the upload finishes (even if I'm on a different screen already).

On Android, I’ve been using Service + BroadcastReceiver or WorkManager. I Can’t find the way of doing it in Flutter.

2 Answers

You can use package https://pub.dev/packages/flutter_uploader
This plugin is based on WorkManager in Android and NSURLSessionUploadTask in iOS to run upload task in background mode.

Create new upload task:

final uploader = FlutterUploader();

final taskId = await uploader.enqueue(
  url: "your upload link", //required: url to upload to
  files: [FileItem(filename: filename, savedDir: savedDir, fieldname:"file")], // required: list of files that you want to upload
  method: UploadMethod.POST, // HTTP method  (POST or PUT or PATCH)
  headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
  data: {"name": "john"}, // any data you want to send in upload request
  showNotification: false, // send local notification (android only) for upload status
  tag: "upload 1"); // unique tag for upload task
);

Listen for upload progress

final subscription = uploader.progress.listen((progress) {
  //... code to handle progress
});

For Snackbar , you can use ScaffoldMessenger to make Snackbar persist across routes https://flutter.dev/docs/release/breaking-changes/scaffold-messenger

The ScaffoldMessenger now handles SnackBars in order to persist across routes and always be displayed on the current Scaffold. By default, a root ScaffoldMessenger is included in the MaterialApp
The ScaffoldMessenger creates a scope in which all descendant Scaffolds register to receive SnackBars, which is how they persist across these transitions. When using the root ScaffoldMessenger provided by the MaterialApp
code snippet

ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: const Text('snack'),
        duration: const Duration(seconds: 1),
        action: SnackBarAction(
          label: 'ACTION',
          onPressed: () { },
        ),
      ));
Related