SlideShare a Scribd company logo
1 of 18
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)

ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
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- ch03
OS-operating systems- ch03OS-operating systems- ch03
OS-operating systems- ch03
 
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
 

Recently uploaded

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

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