Tillitsdone
down Scroll to discover

Using Dio for File Uploads in Flutter Apps

Learn how to implement file uploads in Flutter using Dio HTTP client.

Discover best practices for single and multiple file uploads with progress tracking and error handling.
thumbnail

A modern minimalist abstract composition featuring flowing curves and geometric shapes dominated by bright yellow and orange tones with subtle blue accents shot from top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Using Dio for Uploading Files in Flutter

Have you ever found yourself scratching your head over file uploads in Flutter? Don’t worry – I’ve been there too! Today, we’ll explore how to handle file uploads in Flutter using the powerful Dio package. Whether you’re building a social media app, a document management system, or just need to send files to your backend, this guide has got you covered.

An abstract architectural space with curved walls and large windows natural light streaming through creating geometric patterns sage green and pine green color palette photographed from a low angle looking up high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Setting Up Dio

First things first, let’s add Dio to our project. Open your pubspec.yaml file and add the following dependency:

dependencies:
dio: ^5.4.0

Run flutter pub get, and we’re ready to roll!

Basic File Upload

Let’s start with a simple example of uploading a single file. Here’s how you can implement it:

Future<void> uploadFile(File file) async {
final dio = Dio();
final formData = FormData.fromMap({
'file': await MultipartFile.fromFile(
file.path,
filename: 'upload.jpg',
),
});
try {
final response = await dio.post(
'https://your-api-endpoint.com/upload',
data: formData,
);
print('Upload successful: ${response.data}');
} catch (e) {
print('Error uploading file: $e');
}
}

A serene landscape with rolling hills and a meandering river painted in vibrant lime green tones with darker green accents captured from a drone perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Advanced Features

Progress Tracking

One of the coolest features of Dio is its built-in upload progress tracking. Here’s how to implement it:

Future<void> uploadFileWithProgress(File file) async {
final dio = Dio();
final formData = FormData.fromMap({
'file': await MultipartFile.fromFile(
file.path,
filename: 'upload.jpg',
),
});
try {
await dio.post(
'https://your-api-endpoint.com/upload',
data: formData,
onSendProgress: (sent, total) {
final progress = (sent / total * 100).toStringAsFixed(2);
print('Upload Progress: $progress%');
},
);
} catch (e) {
print('Error uploading file: $e');
}
}

Multiple File Upload

Need to upload multiple files? No problem! Here’s how:

Future<void> uploadMultipleFiles(List<File> files) async {
final dio = Dio();
final formData = FormData();
for (var i = 0; i < files.length; i++) {
formData.files.add(
MapEntry(
'files[]',
await MultipartFile.fromFile(
files[i].path,
filename: 'file_$i.jpg',
),
),
);
}
try {
await dio.post(
'https://your-api-endpoint.com/upload-multiple',
data: formData,
);
} catch (e) {
print('Error uploading files: $e');
}
}

Best Practices and Tips

  1. Always handle errors appropriately and show meaningful messages to users
  2. Consider implementing retry logic for failed uploads
  3. Compress large files before uploading to improve performance
  4. Don’t forget to show loading indicators during uploads
  5. Validate file types and sizes before uploading

Conclusion

Dio makes file uploading in Flutter a breeze! With its robust feature set and straightforward API, you can implement file uploads with just a few lines of code. Remember to handle edge cases and provide a great user experience with progress indicators and error handling.

An abstract geometric composition with intersecting planes and sharp angles featuring bright orange as the dominant color with contrasting blue elements viewed from an isometric angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svgicons/flutter.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.