Creating folder that does not erase when uninstall to save backup - Flutter

Asked

Viewed 504 times

0

I am developing a backup system using path_provider, with the following code.

  // Busca o local que esta o arquivo
  Directory documentsDirectory = await getApplicationDocumentsDirectory();
  final path = join(documentsDirectory.path, 'base.db');
  File sourceFile = File(path);
  List<int> content = await sourceFile.readAsBytes();

  // Define diretório que o arquivo de backup será salvo
  final targetDir = await getExternalStorageDirectory();
  final targetDirFolder = Directory('${targetDir.path}/Backup/');

  final targetPath = join(targetDir.path, 'backup-driive.db');
  File targetFile = File(targetPath);
  await targetFile.writeAsBytes(content, flush: true);

With this code I can save the backup in this folder: "/Storage/Emulated/0/Android/data/br.com.app.combustible/files/arquivodebackup.db", but when the application is uninstalled this folder is removed and does not serve anything "backup", how can I save this file in the internal storage folder of the mobile phone where it is not deleted, I have been searching but found nothing.

  • You have to change the folder where you are saving the backup, when the app is uninstalled android removes the folder br.com.app.combustible and everything in it. Alternatively set up auto backup, https://developer.android.com/guide/topics/data/autobackup

2 answers

1

You can save in Pasture Android Downloads. See below how to save a file in that folder. Remember that this folder is free, the user will have access and can delete the backup. You can name the file with your app name and backup date.

See on original link

Dependencies

dio: ^3.0.0
path_provider: ^1.3.0
simple_permissions: ^0.1.9
file_utils: ^0.1.3

Permissions

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

Code

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'package:simple_permissions/simple_permissions.dart';
import 'package:file_utils/file_utils.dart';
import 'dart:math';

void main() => runApp(Downloader());

 class Downloader extends StatelessWidget {
 @override
 Widget build(BuildContext context) => MaterialApp(
       title: "File Downloader",
      debugShowCheckedModeBanner: false,
      home: FileDownloader(),
      theme: ThemeData(primarySwatch: Colors.blue),
     );
 }

class FileDownloader extends StatefulWidget {
@override
_FileDownloaderState createState() => _FileDownloaderState();
}

class _FileDownloaderState extends State<FileDownloader> {

final imgUrl = "https://images6.alphacoders.com/683/thumb-1920-683023.jpg";
bool downloading = false;
var progress = "";
var path = "No Data";
var platformVersion = "Unknown";
Permission permission1 = Permission.WriteExternalStorage;
var _onPressed;
static final Random random = Random();
Directory externalDir;

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


Future<void> downloadFile() async {
  Dio dio = Dio();
  bool checkPermission1 =
      await SimplePermissions.checkPermission(permission1);
  // print(checkPermission1);
  if (checkPermission1 == false) {
    await SimplePermissions.requestPermission(permission1);
    checkPermission1 = await SimplePermissions.checkPermission(permission1);
  }
  if (checkPermission1 == true) {
    String dirloc = "";
    if (Platform.isAndroid) {
      dirloc = "/sdcard/download/";
    } else {
      dirloc = (await getApplicationDocumentsDirectory()).path;
    }

    var randid = random.nextInt(10000);

    try {
      FileUtils.mkdir([dirloc]);
      await dio.download(imgUrl, dirloc + randid.toString() + ".jpg",
          onReceiveProgress: (receivedBytes, totalBytes) {
        setState(() {
          downloading = true;
          progress =
              ((receivedBytes / totalBytes) * 100).toStringAsFixed(0) + "%";
        });
      });
    } catch (e) {
      print(e);
    }

    setState(() {
      downloading = false;
      progress = "Download Completed.";
      path = dirloc + randid.toString() + ".jpg";
    });
  } else {
    setState(() {
      progress = "Permission Denied!";
      _onPressed = () {
        downloadFile();
      };
    });
  }
}

@override
Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: Text('File Downloader'),
    ),
    body: Center(
        child: downloading
            ? Container(
                height: 120.0,
                width: 200.0,
                child: Card(
                  color: Colors.black,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      CircularProgressIndicator(),
                      SizedBox(
                        height: 10.0,
                      ),
                      Text(
                        'Downloading File: $progress',
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                ),
              )
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(path),
                  MaterialButton(
                    child: Text('Request Permission Again.'),
                    onPressed: _onPressed,
                    disabledColor: Colors.blueGrey,
                    color: Colors.pink,
                    textColor: Colors.white,
                    height: 40.0,
                    minWidth: 100.0,
                  ),
                ],
              )));
  }
  • From what I understand you save the data through the Dio, that downloads a file, but in the case of the question, it is a local file that he wants to back up, he will not be able to use the Dio. And another, you set the path "/sdcard/download/" not always the user will have a sdCard...

  • The answer would be to save in the downloads folder as option so that the backup is not removed. It can use the "plugin ext_storage 1.0.3" and finding the download folder. ExtStorage.getExternalStorageDirectory();

  • Got it, it would be interesting then you have quoted such a package in your reply too... But it’s a good example for him to follow!

0

Have you tried using the command getLibraryDirectory()?

According to what is described in the package source, this command returns a directory that serves to store persistent data and for backups, which is also invisible to the user.

/// Path to the directory where application can store files that are persistent,
/// backed up, and not visible to the user, such as sqlite.db.
///
/// On Android, this function throws an [UnsupportedError] as no equivalent
/// path exists.
Future<Directory> getLibraryDirectory() async {
  final String path = await _platform.getLibraryPath();
  if (path == null) {
    return null;
  }
  return Directory(path);
}
  • I’ll try from here to polco update here

  • I forgot to update, but this solution on android launches an error, according to the documentation only works on IOS devices.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.