SlideShare a Scribd company logo
1 of 18
Download to read offline
Advance Mobile Application
Development
File management in flutter
Dr. Mazin Alkathiri
IT Department
Seiyun University
2023-2024
Working with Files in Flutter
• By using the path_provider plugin we can get the path to common
directories designed for different purposes:
import 'package:path_provider/path_provider.dart';
// Put cache files in this directory
final temporaryDirectory = await getTemporaryDirectory();
// For files that our app uses but are not exposed to the user
final appSupport = await getApplicationSupportDirectory();
// For user-generated files
final appDocuments = await getApplicationDocumentsDirectory();
Create a file
• Let's create a random file in the temporary directory and write
something inside:
final Directory tempDir = await getTemporaryDirectory();
final File file = File('${tempDir.path}/sample_file.txt');
await file.writeAsString('Sample content to write');
Delete a file
• The delete method is just as crucial as the create method, as it helps
clear out old files and thus saves valuable storage space.
final Directory tempDir = await getTemporaryDirectory();
final File file = File('${tempDir.path}/sample_file.txt');
await file.delete();
Create a directory
• Now let's say that I want to create a new file, but within a certain
directory:
final Directory tempDir = await getTemporaryDirectory();
final Directory newDirectory = Directory('${tempDir.path}/sample_directory');
// Always check that the directory exists
if (await newDirectory.exists() == false) {
await newDirectory.create();
}
final File file = File('${newDirectory.path}/sample_file.txt');
await file.writeAsString('Sample content to write');
Remove a directory
• Now let's do the reverse and delete the directory:
final Directory tempDir = await getTemporaryDirectory();
final Directory newDirectory = Directory('${tempDir.path}/sample_directory');
await newDirectory.delete(recursive: true);
Read file
• Let's open a file to see its content:
final Directory tempDir = await getTemporaryDirectory();
final File file = File('${tempDir.path}/sample_file.txt');
final String fileContent = await file.readAsString();
Copy file
• Now, let's generate a duplicate of the previously created sample file:
final Directory tempDir = await getTemporaryDirectory();
final File file = File('${tempDir.path}/sample_file.txt');
final File copy = await file.copy('${tempDir.path}/copy_file.txt');
Rename file
• Next, let's change the name of the file we just copied:
final Directory tempDir = await getTemporaryDirectory();
final File file = File('${tempDir.path}/copy_file.txt');
await file.rename('${tempDir.path}/new_name.txt');
Permission to write
• To allow the user to read and write from the External Storage we
should add the permissions in AndroidManifest.xml
• android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:requestLegacyExternalStorage="true"
Cont.
• We should also make sure the permission to write is Granted before
we start writing a file to the External storage.
var status = await Permission.storage.status;
if (!status.isGranted) {
print("no permistiom");
await Permission.storage.request();
}
// now we can write our files
await file.writeAsString(containt);
An example
• As an example we have
created a dart file called
textfiles.dart
• We a class called Textfile{}
• Containing few functions
such as the shown here ->
• getTemporaryDirectory(); we find the Temporary Directory and
store it in the variable tempDir from type Directory
• File will compaine the Directory along with the file name and
store it in variable filepath from type File
• readAsString(); will read the file given in the variable filepath
and store the content in a String variable called fileContent
which is the return value from readTextFile() function
•
readTextFile() async{
final Directory tempDir = await getTemporaryDirectory();
final File filepath = File('${tempDir.path}/file_picker/a text file 005.txt');
final String fileContent = await file.readAsString();
return(fileContent);
}
• readTextFile2(File? Filepath)
• Reads a specific text file which we passed the file path to.
Future<String> readTextFile2(File? filepath) async{
final String fileContent = await filepath!.readAsString();
return(fileContent);
}
• readTextFile2(File? Filepath)
• Reads the comma separated file line by line and prints the second
value in each line
Future<String> readTextFile3(File? filepath) async{
final List<String> fileContent2 = await filepath!.readAsLines();
int count=0;
for (var i in fileContent2){
//print(i);
if ((count==4) || (count > 6)){
List<String> s=i.split(",");
print(s[1]);
}
• saveTextFile(String filename, String containt)
• writeAsString writes the String Variable content in the file given
in the variable filepath which we pass the both to the function
saveTextFile as parameters.
saveTextFile(String filename, String content) async{
final File filepath = File('/storage/emulated/0/Documents/'+filename+".text");
var status = await Permission.storage.status;
if (!status.isGranted) {
print("no permistiom");
await Permission.storage.request();
}
await filepath.writeAsString(content);
}
• creatDir(String dirname) creates a new Directory with a test text
file.
• We should check if the directory already exists then we don’t
need to create it again
creatDir(String dirname) async {
////////////here we creat a file in side our own Dir in temp folder
final Directory newDirectory = Directory('/storage/emulated/0/'+dirname);
// Always check that the directory exists
if (await newDirectory.exists() == false) {
await newDirectory.create();
}
final File file = File('${newDirectory.path}/sample_file.txt');
print(""+tempDir.toString());
await file.writeAsString('this file writen as the try ');
}
• FilePicker: we use FilePicker to pick a file from the storage and read it
where FilePicker.platform.pickFiles(); will allow us to browses the device
storage and select a file and store it in temporary directore associated
with our app.
ElevatedButton(
onPressed: () async {
try {
result = await FilePicker.platform.pickFiles();
if (result != null) {
if (!kIsWeb) {
file = File(result!.files.single.path!);
filecontaint = (await fileobj.readTextFile2(file)) as Future<String>;
}
} else { print("user cancled the picker"); } // User canceled the picker
} catch (_) {}
super.setState(() { });
},
child: const Text('Pick a Text file File'), ),
import 'package:file_picker/file_picker.dart';

More Related Content

Similar to Advance Mobile Application Development class 02-B

Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Abdullah khawar
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILESHarish Kamat
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8WindowsPhoneRocks
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in CTushar B Kute
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxarmaansohail9356
 
Writing Swift code with great testability
Writing Swift code with great testabilityWriting Swift code with great testability
Writing Swift code with great testabilityJohn Sundell
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxRutujaTandalwade
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 

Similar to Advance Mobile Application Development class 02-B (20)

C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
File handling
File handlingFile handling
File handling
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Writing Swift code with great testability
Writing Swift code with great testabilityWriting Swift code with great testability
Writing Swift code with great testability
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Unix-module3.pptx
Unix-module3.pptxUnix-module3.pptx
Unix-module3.pptx
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 

More from Dr. Mazin Mohamed alkathiri

ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)Dr. Mazin Mohamed alkathiri
 
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)Dr. Mazin Mohamed alkathiri
 
Academic Writing (Technical report writing ) class 07
Academic Writing (Technical report writing ) class 07Academic Writing (Technical report writing ) class 07
Academic Writing (Technical report writing ) class 07Dr. Mazin Mohamed alkathiri
 

More from Dr. Mazin Mohamed alkathiri (20)

Advance Mobile Application Development class 05
Advance Mobile Application Development class 05Advance Mobile Application Development class 05
Advance Mobile Application Development class 05
 
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
 
OS-operating systems- ch02 - part-1-2024
OS-operating systems- ch02 - part-1-2024OS-operating systems- ch02 - part-1-2024
OS-operating systems- ch02 - part-1-2024
 
OS-operating systems - ch02 - part-2-2024
OS-operating systems - ch02 - part-2-2024OS-operating systems - ch02 - part-2-2024
OS-operating systems - ch02 - part-2-2024
 
Advance Mobile Application Development class 04
Advance Mobile Application Development class 04Advance Mobile Application Development class 04
Advance Mobile Application Development class 04
 
Advance Mobile Application Development class 03
Advance Mobile Application Development class 03Advance Mobile Application Development class 03
Advance Mobile Application Development class 03
 
OS-ch02-part-1-2024.ppt
OS-ch02-part-1-2024.pptOS-ch02-part-1-2024.ppt
OS-ch02-part-1-2024.ppt
 
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
 
Advance Mobile Application Development class 01
Advance Mobile Application Development class 01Advance Mobile Application Development class 01
Advance Mobile Application Development class 01
 
ESSENTIAL of (CS/IT/IS) class 02 (HCI)
ESSENTIAL of (CS/IT/IS) class 02 (HCI)ESSENTIAL of (CS/IT/IS) class 02 (HCI)
ESSENTIAL of (CS/IT/IS) class 02 (HCI)
 
Seminar
SeminarSeminar
Seminar
 
ESSENTIAL of (CS/IT/IS)
ESSENTIAL of (CS/IT/IS)ESSENTIAL of (CS/IT/IS)
ESSENTIAL of (CS/IT/IS)
 
OS-ch01-2024.ppt
OS-ch01-2024.pptOS-ch01-2024.ppt
OS-ch01-2024.ppt
 
Mobile Application Development class 008
Mobile Application Development class 008Mobile Application Development class 008
Mobile Application Development class 008
 
Academic Writing (Punctuation ) class 06
Academic Writing (Punctuation ) class 06Academic Writing (Punctuation ) class 06
Academic Writing (Punctuation ) class 06
 
Academic Writing (Technical report writing ) class 07
Academic Writing (Technical report writing ) class 07Academic Writing (Technical report writing ) class 07
Academic Writing (Technical report writing ) class 07
 
Computer Introduction-Lecture07
Computer Introduction-Lecture07Computer Introduction-Lecture07
Computer Introduction-Lecture07
 
Computer Introduction-Lecture06
Computer Introduction-Lecture06Computer Introduction-Lecture06
Computer Introduction-Lecture06
 
Mobile Application Development class 007
Mobile Application Development class 007Mobile Application Development class 007
Mobile Application Development class 007
 
Academic Writing (Writing an abstract) class 06
Academic Writing (Writing an abstract) class 06Academic Writing (Writing an abstract) class 06
Academic Writing (Writing an abstract) class 06
 

Recently uploaded

BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...Nguyen Thanh Tu Collection
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressMaria Paula Aroca
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...DrVipulVKapoor
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
physiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxphysiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxAneriPatwari
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipKarl Donert
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceDr Vijay Vishwakarma
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian Congress
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
physiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxphysiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptx
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenship
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional Intelligence
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 

Advance Mobile Application Development class 02-B

  • 1. Advance Mobile Application Development File management in flutter Dr. Mazin Alkathiri IT Department Seiyun University 2023-2024
  • 2. Working with Files in Flutter • By using the path_provider plugin we can get the path to common directories designed for different purposes: import 'package:path_provider/path_provider.dart'; // Put cache files in this directory final temporaryDirectory = await getTemporaryDirectory(); // For files that our app uses but are not exposed to the user final appSupport = await getApplicationSupportDirectory(); // For user-generated files final appDocuments = await getApplicationDocumentsDirectory();
  • 3. Create a file • Let's create a random file in the temporary directory and write something inside: final Directory tempDir = await getTemporaryDirectory(); final File file = File('${tempDir.path}/sample_file.txt'); await file.writeAsString('Sample content to write');
  • 4. Delete a file • The delete method is just as crucial as the create method, as it helps clear out old files and thus saves valuable storage space. final Directory tempDir = await getTemporaryDirectory(); final File file = File('${tempDir.path}/sample_file.txt'); await file.delete();
  • 5. Create a directory • Now let's say that I want to create a new file, but within a certain directory: final Directory tempDir = await getTemporaryDirectory(); final Directory newDirectory = Directory('${tempDir.path}/sample_directory'); // Always check that the directory exists if (await newDirectory.exists() == false) { await newDirectory.create(); } final File file = File('${newDirectory.path}/sample_file.txt'); await file.writeAsString('Sample content to write');
  • 6. Remove a directory • Now let's do the reverse and delete the directory: final Directory tempDir = await getTemporaryDirectory(); final Directory newDirectory = Directory('${tempDir.path}/sample_directory'); await newDirectory.delete(recursive: true);
  • 7. Read file • Let's open a file to see its content: final Directory tempDir = await getTemporaryDirectory(); final File file = File('${tempDir.path}/sample_file.txt'); final String fileContent = await file.readAsString();
  • 8. Copy file • Now, let's generate a duplicate of the previously created sample file: final Directory tempDir = await getTemporaryDirectory(); final File file = File('${tempDir.path}/sample_file.txt'); final File copy = await file.copy('${tempDir.path}/copy_file.txt');
  • 9. Rename file • Next, let's change the name of the file we just copied: final Directory tempDir = await getTemporaryDirectory(); final File file = File('${tempDir.path}/copy_file.txt'); await file.rename('${tempDir.path}/new_name.txt');
  • 10. Permission to write • To allow the user to read and write from the External Storage we should add the permissions in AndroidManifest.xml • android/app/src/main/AndroidManifest.xml <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:requestLegacyExternalStorage="true"
  • 11. Cont. • We should also make sure the permission to write is Granted before we start writing a file to the External storage. var status = await Permission.storage.status; if (!status.isGranted) { print("no permistiom"); await Permission.storage.request(); } // now we can write our files await file.writeAsString(containt);
  • 12. An example • As an example we have created a dart file called textfiles.dart • We a class called Textfile{} • Containing few functions such as the shown here ->
  • 13. • getTemporaryDirectory(); we find the Temporary Directory and store it in the variable tempDir from type Directory • File will compaine the Directory along with the file name and store it in variable filepath from type File • readAsString(); will read the file given in the variable filepath and store the content in a String variable called fileContent which is the return value from readTextFile() function • readTextFile() async{ final Directory tempDir = await getTemporaryDirectory(); final File filepath = File('${tempDir.path}/file_picker/a text file 005.txt'); final String fileContent = await file.readAsString(); return(fileContent); }
  • 14. • readTextFile2(File? Filepath) • Reads a specific text file which we passed the file path to. Future<String> readTextFile2(File? filepath) async{ final String fileContent = await filepath!.readAsString(); return(fileContent); }
  • 15. • readTextFile2(File? Filepath) • Reads the comma separated file line by line and prints the second value in each line Future<String> readTextFile3(File? filepath) async{ final List<String> fileContent2 = await filepath!.readAsLines(); int count=0; for (var i in fileContent2){ //print(i); if ((count==4) || (count > 6)){ List<String> s=i.split(","); print(s[1]); }
  • 16. • saveTextFile(String filename, String containt) • writeAsString writes the String Variable content in the file given in the variable filepath which we pass the both to the function saveTextFile as parameters. saveTextFile(String filename, String content) async{ final File filepath = File('/storage/emulated/0/Documents/'+filename+".text"); var status = await Permission.storage.status; if (!status.isGranted) { print("no permistiom"); await Permission.storage.request(); } await filepath.writeAsString(content); }
  • 17. • creatDir(String dirname) creates a new Directory with a test text file. • We should check if the directory already exists then we don’t need to create it again creatDir(String dirname) async { ////////////here we creat a file in side our own Dir in temp folder final Directory newDirectory = Directory('/storage/emulated/0/'+dirname); // Always check that the directory exists if (await newDirectory.exists() == false) { await newDirectory.create(); } final File file = File('${newDirectory.path}/sample_file.txt'); print(""+tempDir.toString()); await file.writeAsString('this file writen as the try '); }
  • 18. • FilePicker: we use FilePicker to pick a file from the storage and read it where FilePicker.platform.pickFiles(); will allow us to browses the device storage and select a file and store it in temporary directore associated with our app. ElevatedButton( onPressed: () async { try { result = await FilePicker.platform.pickFiles(); if (result != null) { if (!kIsWeb) { file = File(result!.files.single.path!); filecontaint = (await fileobj.readTextFile2(file)) as Future<String>; } } else { print("user cancled the picker"); } // User canceled the picker } catch (_) {} super.setState(() { }); }, child: const Text('Pick a Text file File'), ), import 'package:file_picker/file_picker.dart';