Web Analytics Made Easy -
StatCounter
download-file-with-linear-progress-bar-flutter-dart-dio

In this article, we will explorehow to download a file from a URL in Flutter with a linear progress bar. The dio package which supports handling form data, interceptors, etc is used to handleHTTP client requests.

Requirements

dio.download

A method used to download a document.

onReceiveProgress

A property used to get download progress.

getExternalStorageDirectory

A function is used to get the path where an application is installed.

Dependencies

Add the below dependencies to the pubspec.yaml file:

dio: any
path_provider: any

Packages

Import the below packages in the widget:

import ‘package:dio/dio.dart’;
import ‘package:flutter/material.dart’;
import ‘package:path_provider/path_provider.dart’;

Flutter Download Progress With Linear Indicator

Let’s create a widget to show the linear download progress
Center(

        child: Column(

          mainAxisSize: MainAxisSize.min,

          children: [

            const Text(

              'Dio Package',

              style: TextStyle(

                fontSize: 24,

                fontWeight: FontWeight.w600,

                color: Colors.black54,

              ),

            ),

            const SizedBox(

              height: 50,

            ),

            ElevatedButton.icon(

              onPressed: () => dioDownloadFile(),

              icon: const Icon(Icons.download),

              label: const Text('Download'),

            ),

            Padding(

              padding: const EdgeInsets.all(8.0),

              child: LinearProgressIndicator(

                backgroundColor: Colors.black38,

                minHeight: 10,

                value: _percentage,

              ),

            ),

            Text(

              downloadStatus ?? '',

              style: const TextStyle(

                fontSize: 16,

                fontWeight: FontWeight.w600,

                color: Colors.black54,

              ),

            ),

          ],

        ),

      ),
Next, let’s create a method to download a file using dio
  void dioDownloadFile() async {

    var dir = await getExternalStorageDirectory();


    Dio dio = Dio();

    try {

      const String url =

          'https://www.sample-videos.com/img/Sample-jpg-image-15mb.jpeg';

      await dio.download(

        url,

        '${dir?.path}/fileNameHere.jpeg',

        onReceiveProgress: (actual, total) {

          double progressPercentage = actual / total * 100;

          if (progressPercentage < 100) {

            _percentage = progressPercentage / 100;

            setState(() {

              downloadStatus = 'Downloading...';

            });

          } else {

            setState(() {

              downloadStatus = 'Downloaded';

            });

          }

        },

      );

    } catch (error) {

      debugPrint(error.toString());

    }

  }
Complete Source Code
import 'package:dio/dio.dart';

import 'package:flutter/material.dart';

import 'package:path_provider/path_provider.dart';


class LinearDownloadProgressDio extends StatefulWidget {

  const LinearDownloadProgressDio({super.key});


  @override

  State createState() =>

      _LinearDownloadProgressDioState();

}


class _LinearDownloadProgressDioState extends State {

  double _percentage = 0;

  String? downloadStatus;

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text(

          'Linear Download Progress',

          style: TextStyle(fontSize: 14),

        ),

      ),

      body: Center(

        child: Column(

          mainAxisSize: MainAxisSize.min,

          children: [

            const Text(

              'Dio Package',

              style: TextStyle(

                fontSize: 24,

                fontWeight: FontWeight.w600,

                color: Colors.black54,

              ),

            ),

            const SizedBox(

              height: 50,

            ),

            ElevatedButton.icon(

              onPressed: () => dioDownloadFile(),

              icon: const Icon(Icons.download),

              label: const Text('Download'),

            ),

            Padding(

              padding: const EdgeInsets.all(8.0),

              child: LinearProgressIndicator(

                backgroundColor: Colors.black38,

                minHeight: 10,

                value: _percentage,

              ),

            ),

            Text(

              downloadStatus ?? '',

              style: const TextStyle(

                fontSize: 16,

                fontWeight: FontWeight.w600,

                color: Colors.black54,

              ),

            ),

          ],

        ),

      ),

    );

  }


  void dioDownloadFile() async {

    var dir = await getExternalStorageDirectory();


    Dio dio = Dio();

    try {

      const String url =

          'https://www.sample-videos.com/img/Sample-jpg-image-15mb.jpeg';

      await dio.download(

        url,

        '${dir?.path}/fileNameHere.jpeg',

        onReceiveProgress: (actual, total) {

          double progressPercentage = actual / total * 100;

          if (progressPercentage < 100) {

            _percentage = progressPercentage / 100;

            setState(() {

              downloadStatus = 'Downloading...';

            });

          } else {

            setState(() {

              downloadStatus = 'Downloaded';

            });

          }

        },

      );

    } catch (error) {

      debugPrint(error.toString());

    }

  }

}

If now we run the app and then tap on the download button, we can see the file will be downloaded with a linear progress bar as shown below in the video.

Linear Progress Bar Flutter

Conclusion

In this article, we get to knowhow to use dio package to show linear download progress in a flutter.

Avatar

By AmmarJaved

Ammar Javed possesses a unique combination of skills and expertise in web, desktop, and mobile app development, and content writing. Ammar Javed is a strategic thinker and has problem-solving abilities. Ammar Javed can work independently and in a team. Ammar Javed is dedicated to continuous learning and professional development.

Leave a Reply

Your email address will not be published. Required fields are marked *