Flutter: Uploading Files with GetConnect (GetX)

Updated: July 25, 2022 By: A Goodman Post a comment

At the time of writing, GetX (aka Get) is the most-liked Flutter package (9.7k+ likes). This multi-purpose library provides a bunch of features, including state management, navigation & routing. You can also upload files to a remote server by taking advantage of the GetConnect class provided by GetX. There is no need to install other HTTP packages like http or dio.

Below is how to upload multiple files by sending form data (multipart/form-data) in a POST request with GetConnect:

1. Import required packages:

import 'package:get/get.dart';
import 'dart:io';

2. Upload some images at one with GetConnect’s post() method:

// kindacode.com
// uploading multiple files with GetX: example

// Create an instance of GetConnect
final GetConnect _connect = GetConnect(
      // the request will fail if it takes more than 10 seconds
      // you can use another value if you like
      timeout: const Duration(seconds: 10),
);

// construct form data
// you can upload multiple files in a single POST request
final FormData _formData = FormData({
      'file1': MultipartFile(File('path to file1'), filename: 'kindacode.jpg'),
      'file2': MultipartFile(File('path to file 2'), filename: 'kindacode.png'),
      'file3': MultipartFile(File('path to file 3'), filename: 'kindacode.gif'),
      'otherData': {/* other data */}
});

// Send FormData in POST request to upload file
try {
      final Response res =
          await _connect.post('your API URL here', _formData, headers: {
        /* headers information like Authorization, Cookie, etc */
      });

      // Do something with the response
      print(res.body);
} catch (err) {
      // Handle errors
      print(err);
}

If you haven’t worked with a file picker before, see this article: How to implement an image picker in Flutter. You can improve the sample code above or change some things to make it fit your needs.

Further reading:

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles