Flutter - Local files importation - flutter

i would like to import in my flutter application, files from "Files" and "Photos" default ios/android/macos applications.
Have you got any solution to do that ?
Thank you

See this documentation: https://docs.flutter.dev/cookbook/persistence/reading-writing-files
add to pubspec (https://pub.dev/packages/path_provider):
path_provider: ^2.0.11
import package:
import 'package:path_provider/path_provider.dart';
Find local path:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
create reference:
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
read data:
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}

You can use image_picker package to access user's photos with the required permissions;
iOS
Android

You can use the flutter File Picker package.
https://pub.dev/packages/file_picker

Related

Get a list of files from the local storage and display it as a list in flutter web:

I've been building an ios app and in it, it'll download a bunch of pdf from an API and save it to the local storage using the path_provider package in flutter:
This is the code I use to fetch the path:
Future<String> get localPath async {
final directory = await getApplicationDocumentsDirectory();
currentDir.value = directory.path;
return directory.path;}
And this is how I save it to the device:
Future<void> saveFilesToLocal(String url, String fileName) async {
try {
final path = await localPath;
final file = File('$path/$fileName');
if (await file.exists() == false) {
final response = await Dio().get(url,
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
receiveTimeout: 0));
final raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
} else {
print("file already exists");
}
} catch (e) {
print('error: $e');
}
}
After I download and save the files to the storage, it'll be displayed as a gridview in the home page. To fetch that list of files I use this:
List<FileSystemEntity> files = [];
Future<void> getFilesList() async {
files.clear();
final path = await localPath;
Directory dir = Directory('$path');
files =
dir.listSync(recursive: true, followLinks: false);
update();
}
And all of this works fine in the ios device. But the current issue I'm facing while trying to run it on web is:
The package path_provider is not available for flutter web. I've been asked to create it as a web app too and I can't find an alternative for it. While looking for one I saw a post saying flutter web won't allow access to a device's local storage like that so it's not possible. Is it true? Is there a workaround? If it's about security, the app will only be run on specific devices. It won't be given to the public.

How to save video to phone gallery - Dio/Flutter

I'm trying to save the video in the phone gallery (downloaded using dio package) To get the path, I'm using path provider package but unable to save it in the phone gallery
Here is my code
void downloadVideo() async {
var dir = await getExternalStorageDirectory();
final dio = Dio();
dio.download(
'video_url',
'${dir!.path}/video.mp4', // saving path, I'm trying to save it in phone gallery
onReceiveProgress: (actualBytes, totalBytes){
var percentage = actualBytes/totalBytes*100;
}
);
}
Note:- I'm aware of gallery_saver package but I need to achieve this using dio and path provider
So you already have the saving directory. You can use plugins like image_gallery_saver and gallery_saver to save your downloaded video to the gallery.
If you use image_gallery_saver, the saving code would be similar to this:
await ImageGallerySaver.saveFile(finalVideoPath);
And don't forget to delete the video in the download path after saving the video successfully to the gallery.
Final code:
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<void> downloadVideo() async {
final appDocDirectory = await getAppDocDirectory();
final finalVideoPath = join(
appDocDirectory.path,
'Video-${DateTime.now().millisecondsSinceEpoch}.mp4',
);
final dio = Dio();
await dio.download(
'video_url',
finalVideoPath,
onReceiveProgress: (actualBytes, totalBytes) {
final percentage = actualBytes / totalBytes * 100;
},
);
await saveDownloadedVideoToGallery(videoPath: finalVideoPath);
await removeDownloadedVideo(videoPath: finalVideoPath);
}
Future<Directory> getAppDocDirectory() async {
if (Platform.isIOS) {
return getApplicationDocumentsDirectory();
}
return (await getExternalStorageDirectory())!;
}
Future<void> saveDownloadedVideoToGallery({required String videoPath}) async {
await ImageGallerySaver.saveFile(videoPath);
}
Future<void> removeDownloadedVideo({required String videoPath}) async {
try {
Directory(videoPath).deleteSync(recursive: true);
} catch (error) {
debugPrint('$error');
}
}

Cannot create a file in flutter

I have tried this code below but an empty folder i have found and still cannot create a file, but no errors found in the terminal.
here is the packages i have used :
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
this is the codes to create the file, is there something wrong:
Future<String> getFilePath() async {
Directory? appExtDirectory = await getExternalStorageDirectory();
String appExtPath = appExtDirectory.toString();
print('$appExtPath');
return appExtPath;
}
Future<File> get _localFile async {
final path = await getFilePath();
return File('$path/counter.txt');
}
Future<File> writeCounter() async {
final file = await _localFile;
// Write the file
return file.writeAsString("This is my demo text that will be saved to : counter.txt");
}
void saveFile() {
writeCounter();
}
Regards..
Try String appExtPath = appExtDirectory.path;

How to implement Flutter clear user app data and storage on logout

How to implement Flutter App clear user app data and storage on logout..
i want to clear everything (shared preferences, global variables, singletons, local storage, cache)
this should be equivalent to Android > settings > App > clear storage & clear cache..
first install path_provider
/// this will delete cache
Future<void> _deleteCacheDir() async {
final cacheDir = await getTemporaryDirectory();
if (cacheDir.existsSync()) {
cacheDir.deleteSync(recursive: true);
}
}
/// this will delete app's storage
Future<void> _deleteAppDir() async {
final appDir = await getApplicationSupportDirectory();
if(appDir.existsSync()){
appDir.deleteSync(recursive: true);
}
}
see the original answer here
you must use from path_provider to get your app TemporaryDirectory and app Directory
on the filesystem.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
Future<void> _deleteCacheDir() async {
Directory tempDir = await getTemporaryDirectory();
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
}
Future<void> _deleteAppDir() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
if (appDocDir.existsSync()) {
appDocDir.deleteSync(recursive: true);
}
}

Create Folder When Installing Application

How to create folder in device storage to save files?
This is the code to download file into device :
import 'package:flutter_downloader/flutter_downloader.dart';
onTap: () async { //ListTile attribute
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
final taskId = await FlutterDownloader.enqueue(
url: 'http://myapp/${attach[index]}',
savedDir: '/sdcard/myapp',
showNotification: true, // show download progress in status bar (for Android)
clickToOpenDownloadedFile: true, // click on notification to open downloaded file (for Android)
);
},
You can create directory when app is launched.
In the initState() method of your first screen do the logic.
Ex.
createDir() async {
Directory baseDir = await getExternalStorageDirectory(); //only for Android
// Directory baseDir = await getApplicationDocumentsDirectory(); //works for both iOS and Android
String dirToBeCreated = "<your_dir_name>";
String finalDir = join(baseDir, dirToBeCreated);
var dir = Directory(finalDir);
bool dirExists = await dir.exists();
if(!dirExists){
dir.create(/*recursive=true*/); //pass recursive as true if directory is recursive
}
//Now you can use this directory for saving file, etc.
//In case you are using external storage, make sure you have storage permissions.
}
#override
initState(){
createDir(); //call your method here
super.initState();
}
You need to import these libraries:
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
From what I saw is, you are not using appDocDir and appDocPath anywhere, cause you are saving files in /sdcard/myapp.
Please check if you are asking and granting the storage permission and also there is no way to store files in sdcard like you are doing. Either make use of predefined directories like (Document, Pictures etc.) or use device root directory that starts with storage/emulated/0
//add in pubspec.yaml
path_provider:
//import this
import 'dart:io' as io;
import 'package:path_provider/path_provider.dart';
//create Variable
String directory = (await getApplicationDocumentsDirectory()).path;
//initstate to create directory at launch time
#override
void initState() {
// TODO: implement initState
super.initState();
createFolder();
}
//call this method from init state to create folder if the folder is not exists
void createFolder() async {
if (await io.Directory(directory + "/yourDirectoryName").exists() != true) {
print("Directory not exist");
new io.Directory(directory + "/your DirectoryName").createSync(recursive: true);
//do your work
} else {
print("Directoryexist");
//do your work
}
}
Here is the Sample Codefor Creating a folder in Users internal storage Hope it Helps You
import 'dart:io' as Io;
Future _downloadImage() async {
try {
// request runtime permission
final permissionHandler = PermissionHandler();
final status = await permissionHandler
.checkPermissionStatus(PermissionGroup.storage);
if (status != PermissionStatus.granted) {
final requestRes = await permissionHandler
.requestPermissions([PermissionGroup.storage]);
if (requestRes[PermissionGroup.storage] != PermissionStatus.granted) {
_showSnackBar('Permission denined. Go to setting to granted!');
return _done();
}
}
}
var testdir =
await new Io.Directory('/storage/emulated/0/MyApp').create(recursive: true);
final filePath =
path.join(testdir.path, Filename + '.png');
print(filePath);
final file = File(filePath);
if (file.existsSync()) {
file.deleteSync();
}
//save image to storage
var request = await HttpClient().getUrl(Uri.parse(imageUrl));
var response = await request.close();
final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
final saveFileResult =
saveImage({'filePath': filePath, 'bytes': bytes});
_showSnackBar(
saveFileResult
? 'Image downloaded successfully'
: 'Failed to download image',
);
} on PlatformException catch (e) {
_showSnackBar(e.message);
} catch (e, s) {
_showSnackBar('An error occurred');
debugPrint('Download image: $e, $s');
}
return _done();
}
First you need to import
1) import 'dart:io';
Second you need to create directory for the specified path in your async/await function
2) For example:
await new Directory('/storage/emulated/0/yourFolder').create(recursive: true);