Download and save to private app document dir

import 'dart:developer';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class FF extends StatefulWidget {
  const FF({super.key});

  @override
  State createState() => _FFState();
}

class _FFState extends State {
  bool downloading = false;
  var progress = "";

  @override
  void initState() {
    super.initState();
    getDir();
  }

  Future _checkPermission() async {
    return true;
  }

  var _localPath;
  Future _prepareSaveDir() async {
    _localPath = (await createFolderInAppDocDir('MainData'));

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

  Future createFolderInAppDocDir(String folderName) async {
    //Get this App Document Directory

    final Directory appDocDir = await getApplicationDocumentsDirectory();
    //App Document Directory + folder name
    final Directory appDocDirFolder =
        Directory('${appDocDir.path}/$folderName/');

    if (await appDocDirFolder.exists()) {
      //if folder already exists return path
      return appDocDirFolder.path;
    } else {
      //if folder not exists create folder and then return its path
      final Directory appDocDirNewFolder =
          await appDocDirFolder.create(recursive: true);
      return appDocDirNewFolder.path;
    }
  }

  List _folders = [];
  Future getDir() async {
    final directory = await getApplicationDocumentsDirectory();
    final dir = directory.path;
    String pdfDirectory = '$dir/UserData';
    final myDir = Directory(pdfDirectory);
    setState(() {
      _folders = myDir.listSync(recursive: true, followLinks: false);
    });
    print(_folders);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: InkWell(
          onTap: () async {
            var permissionReady = await _checkPermission();
            if (permissionReady) {
              await _prepareSaveDir();
              print("Downloading");
              try {
                await Dio().download(
                    "https://raw.githubusercontent.com/fluttercommunity/flutter_downloader/master/screenshot/enable_background_mode.png",
                    onReceiveProgress: (count, total) {
                  progress = "${((count / total) * 100).toStringAsFixed(0)}%";
                }, _localPath + "/" + "filename.jpg");
                print("Download Completed.");
              } catch (e) {
                print("Download Failed.\n\n$e");
              }
            }
          },
          child: Container(
            child: const Text('dn'),
          )),
    );
  }
}

Post a Comment

Previous Post Next Post