Flutter: exporting file to phone storage - flutter

I'm trying to export a txt file as srt (which is written in plain text) in my app and it is working in the sense that I see srt's with the correct name in the specified folder but these files are 0B and I'm not sure where what is not fully working?
void add() async {
fileName = _fileNameCon.text.toString();
print("filename ---------> " + fileName);
newSubFile(fileName);
setState(() {
_fileNameCon.clear();
srt = "";
subnumber = 1;
stopWatch.reset();
});
}
void newSubFile(String title) async {
try {
// this is an android specific directory
Directory directory = await getExternalStorageDirectory();
final path = directory.path;
File newSrt = await File('$path/' + title + ".srt").create();
var writer = newSrt.openWrite();
print("----attempting to write to $path/$title----");
writer.write(srt);
writer.close();
print("----closing----");
} catch (e) {
print(e);
}
}

Imports
import 'dart:io'
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Example:
Directory dir = await getExternalStorageDirectory();
final file = File(join('${dir.parent}/sub folder',"Output.srt"));
await file.writeAsString(subtitles)

Related

Flutter base64 pdf view and download

Here comes the pdf converted to base64 from an API. I cannot view and download from within the application. I would be glad if you help.
Thanks in advance.
First you need to add "path_provider" and "open_file"
dependencies:
path_provider: ^2.0.9
open_file: ^3.2.1
Then create new class
class FileProcess {
static bool isFolderCreated = false;
static Directory? directory;
static checkDocumentFolder() async {
try {
if (!isFolderCreated) {
directory = await getApplicationDocumentsDirectory();
await directory!.exists().then((value) {
if (value) directory!.create();
isFolderCreated = true;
});
}
} catch (e) {
print(e.toString());
}
}
static Future<File> downloadFile() async {
final base64str = "put your base64 value";
Uint8List bytes = base64.decode(base64str);
await checkDocumentFolder();
String dir =
directory!.path + "/" + "your file name" + ".pdf";
File file = new File(dir);
if (!file.existsSync()) file.create();
await file.writeAsBytes(bytes);
return file;
}
}
After you create the class you can use it for download your pdf.
For open the file add this lines into your class
static void openFile(String fileName) {
String dir =
directory!.path + "/${fileName}.pdf";
OpenFile.open(dir));
}
After all you can use like
await FileProcess.downloadFile()
and
FileProcess.openFile(fileName)
These codes should be working.

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;

Flutter file is written but nowhere to be found

See the following code:
import 'package:path_provider/path_provider.dart';
Directory? directory = await getExternalStorageDirectory();
String id = "z8PANL7qgbg9XJOQQZM2V9RnP5nESNvi";
try {
String fullPathName = directory.path + '/' + id + '.jpg';
file = File(fullPathName).writeAsBytes(data);
print("success $fullPathName");
}
I get the following output:
success /storage/emulated/0/Android/data/com.example.myapp/files/z8PANL7qgbg9XJOQQZM2V9RnP5nESNvi.jpg
It seems that the file is successfully written but then when I try to see the file (an image), with ImagePicker, it is impossible to find it anywhere.
NB: I use Android emulator.
you can use this way
import 'package:image/image.dart' as ImD;
File file;
photoAdress() async {
final directory = await getTemporaryDirectory();
final path= directory .path;
ImD.Image photo= ImD.decodeImage(dosya.readAsBytesSync());
var formed= File("$path/img_$gonderiID.jpg")..writeAsBytesSync(ImD.encodeJpg(photo, quality: 90));
setState(() {
file= formed;
});
}

Reading from text files until String max length

I'm new to coding in Dart so please bear with me. I searched up how to read files with the readAsString() function from the flutter API. It says that it will read the entire content of the file and return it as a String. However, is there some sort of String max size that it can only read? I could not find the max size of a String in Dart online. Thanks.
Here's the code in case you want a look:
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class Storage {
Future<String> get localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get localFile async {
final path = await localPath;
return File('$path/data.txt');
}
Future<List<String>> read() async {
try {
final file = await localFile;
String contents = await file.readAsString(); //the important part
return contents.split(";");
} catch (exception) {
return null;
}
}
void write(List data) async {
final file = await localFile;
String toWrite = "";
for (int i = 0; i < data.length; i++) {
toWrite += data.elementAt(i) + ";";
}
file.writeAsString(toWrite);
}
}
Maybe you want something like:
var myFileStream = File('path/to/file').openRead();
var firstChars = myFileStream.take(1024);
This will limit the memory part of the file to the first 1024 characters.
(I think. :)

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);