Flutter Tutorial

flutter Download csv file and save in downloads folder

Download csv file and save in downloads folder in flutter

Hi Flutter developer in this flutter  tutorial I am share how to download csv file in flutter. And save the download folder. Like in your App have a requirement to download a csv file form URL So for that I am using path_provider  and permission_handler dependency in your pubspec.yaml file.

This is working your both platform android and ios so you need to add permission also for access the internal stores. on the UI once you click on download button firstly check the permission is allow or not. if permission is not allow the show a popup for allow the stores permission. After the csv file is download and store the download folder.

Download csv file With the help of this code you can download any type of file line image, pdf, csv, video, you can just change the file mime type like file.pdf, image.png, image.jpeg, myvideo.mp4 etc.

How to Download csv file and save in downloads folder in flutter?

Android  Add Permission. 

firstly you can add the internet permission and write external store in android manifest file.

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

And Also add in application

android:requestLegacyExternalStorage="true"

Ios Add info.Plist

<true/>
<key>UISupportsDocumentBrowser</key>
   <true/>

 

Flutter pubspec.ymal file 

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  dio: ^4.0.0
  path_provider: ^2.0.2
  permission_handler: ^8.0.0+2
  open_file_plus: ^3.4.1

Add Above dependencies and get your pub. to access all these dependencies. And lest start to make a UI for Download csv file and save in downloads folder in flutter. open your main. dart file and follow below code snip for Download csv file.

Download csv file and save in downloads folder in flutter.

Main.Dart file Source Code 

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:firstapp/AppShowCash.dart';
import 'package:flutter/material.dart';
import 'package:open_file_plus/open_file_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  late String _localPath;
  late bool _permissionReady;
  late TargetPlatform? platform;
  var _openResult = 'Unknown';

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) {
      platform = TargetPlatform.android;
    } else {
      platform = TargetPlatform.iOS;
    }
  }

  Future<bool> _checkPermission() async {
    if (platform == TargetPlatform.android) {
      final status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        final result = await Permission.storage.request();
        if (result == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  Future<void> _prepareSaveDir() async {
    _localPath = (await _findLocalPath())!;

    print(_localPath);
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
  }

  Future<String?> _findLocalPath() async {
    if (platform == TargetPlatform.android) {
      return "/sdcard/download/";
    } else {
      var directory = await getApplicationDocumentsDirectory();
      return directory.path + Platform.pathSeparator + 'Download';
    }
  }

  Future<void> openFile() async {
    final filePath = _localPath+"/" + "codeplayon.csv";
    final result = await OpenFile.open(filePath);

    setState(() {
      _openResult = "type=${result.type}  message=${result.message}";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            GestureDetector(
              onTap: () {

              },
                child: Text("Notification",style: TextStyle(fontSize: 20),)),
            SizedBox(height: 20,),
        InkWell(
            onTap: () async {
              _permissionReady = await _checkPermission();
              if (_permissionReady) {
                await _prepareSaveDir();
                print("Downloading");
                try {
                  await Dio().download("https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv",
                      _localPath +"/" + "codeplayon.csv");
                  print("Download Completed.");
                  openFile();
                } catch (e) {
                  print("Download Failed.\n\n" + e.toString());
                }
              }
            },
            child: Container(
              decoration: BoxDecoration(
                  shape: BoxShape.circle, color: Colors.grey.withOpacity(0.5)),
              padding: EdgeInsets.all(8),
              child: Icon(Icons.download, color: Colors.black),
            )),


          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

After adding the code run your App and click on download icons. after download completed check your Download csv file in the mobile download folder.

 

Read More Tutorial