Skip to content

Instantly share code, notes, and snippets.

@omarzer0
Created February 2, 2023 16:04
Show Gist options
  • Save omarzer0/87d072909d3efe46be5400739c47ded0 to your computer and use it in GitHub Desktop.
Save omarzer0/87d072909d3efe46be5400739c47ded0 to your computer and use it in GitHub Desktop.
Files Files
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Screen(),
),
);
}
Future<String> getPath() async {
final folder = await getApplicationDocumentsDirectory();
return folder.path;
}
void createFile() async {
String path = await getPath();
// File file = File("$path/codes.txt");
// file.create();
File file = File("$path/books.txt");
// file.writeAsString("Go to school");
file.writeAsString("\nGo to hell", mode: FileMode.append);
file.writeAsString("مدرستي قبيحة", mode: FileMode.append, encoding: utf8);
}
void readFromFile() async {
String path = await getPath();
File file = File("$path/books.txt");
String data = await file.readAsString();
print(data);
}
void deleteFile() async {
String path = await getPath();
File file = File("$path/codes.txt");
file.delete();
}
void createFolder() async {
String path = await getPath();
Directory dir = Directory("$path/songs");
dir.create();
}
void deleteFolder() async {
String path = await getPath();
Directory dir = Directory("$path/songs");
if (await dir.exists()) {
dir.delete(recursive: true);
}
}
void listFilesInFolder() async {
String path = await getPath();
Directory dir = Directory("$path/books");
dir.list(recursive: true).forEach((element) async{
String fileName = basename(element.path);
bool directory = await isDirectory(element.path);
print("$fileName -> ${directory ? "Folder" : "File"}");
});
}
Future<bool> isDirectory(String path) async{
return await Directory(path).exists();
}
class Screen extends StatelessWidget {
const Screen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test file"),
),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
createFolder();
},
child: Text("Create Folder"),
),
ElevatedButton(
onPressed: () {
listFilesInFolder();
},
child: Text("List files in Folder"),
),
ElevatedButton(
onPressed: () {
deleteFolder();
},
child: Text("Delete Folder"),
),
ElevatedButton(
onPressed: () {
createFile();
},
child: Text("Create file"),
),
ElevatedButton(
onPressed: () {
readFromFile();
},
child: Text("Read file"),
),
ElevatedButton(
onPressed: () {
deleteFile();
},
child: Text("Delete file"),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment