How to download files in Flutter? And read.

From now and then, you might be building an app where you need to download a file or two from the internet, store it locally and then display it on the phone. Let\’s say, a chat application would require the videos, images, audios for that purpose. What to do then?

Flutter has the capability to let you store files locally but for this example, we would use the famous library for API calls, dio.

Once you have installed dio on your application, add permissions in AndroidManifest for allowing to read and write files.

<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>
<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/>

Of course if you would like the application to ask the user for writing permission, use a permission_handler.

For downloading a file, below is the function which will take the URL for your media and the name you would like it to store as. The function then gets the applications directory on the phone, makes a file and then downloads the media to that file.

downloadUsingDio(String mediaURL, String fileName) async {
Dio dio = Dio();
await getApplicationDocumentsDirectory().then((appDir) async {
var filePath = await File(appDir.path + \'/\' + fileName).create(recursive: true);
var myFile = await, filePath.path);

If the file you downloaded is an image, you can then get that path and use it in a Image.File(\'path_of_the_media_download\').

For more information about read and write files on flutter, please click here.



, ,



Leave a Reply

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