I think this is one of the crucial and most important functionalities to read and write a file. Flutter also supports reading and writing files programmatically. You can use this tutorial as a reference to read and write any kind of text, doc, json or any other file types.
For this tutorial we are gonna cover following contents
- Read files from the assets
- Read files from your android or ios devices
- Write files from your android or ios devices
So some of you might think how to write files at assets folder. But, at the moment I’m writing this content I didn’t found any suitable way to do so from official flutter docs. I will keep checking this functionality and will update as soon as it will be available from official flutter docs.
First thing first, for implementing this file manipulating feature we are gonna use a third party package Path_Provider to access commonly used file locations on the file system.
Path_Provider is required only if you want to read and write files to your android/ios device locations.
Now, let’s get started with reading and writing files to your flutter projects.
Read files from the assets
To read files from assets you have to create or add your file(whether it is txt, doc, json etc.) in to assets folder. So first create a folder named “assets” inside your root project folder. Then create or add your file. For our sample I’m creating a file named “Toastguyz.txt” with some text inside it.
To access any files from assets in flutter, you need to register them inside pubspec.yaml file.
Pubspec.yaml file
assets:
– assets/Toastguyz.txt
To access any files from assets in flutter, you need to register them inside pubspec.yaml file.
readFilesFromAssets() async {
// Users can load any kind of files like txt, doc or json files as well
String assetContent = await rootBundle.loadString('assets/Toastguyz.txt');
print("assetContent : ${assetContent}");
}
You will need to use services dependency/APIs to use rootBundle related features.
import ‘package:flutter/services.dart’;
For our user case, I have accessed a text file using above method. You can also use other file types like doc, json and many more.
That’s it for read and write files from assets.
Read files from your android or ios devices
To read files from your custom android or ios location, you must have a file at that location. So, we will first create a file at some custom location in our android/ios devices and then we will try to read data from that file.
So to access custom file system location we will use a third party package called Path_Provider. It will help us to easily access file locations as per our requirements.
In our main.dart file, I have created a Home class inside which I have added a button to read files from android or ios device locations. Following is the method I have added to read files from custom device locations.
readFilesFromCustomDevicePath() async {
// Retrieve "External Storage Directory" for Android and "NSApplicationSupportDirectory" for iOS
Directory directory = Platform.isAndroid
? await getExternalStorageDirectory()
: await getApplicationSupportDirectory();
// Create a new file. You can create any kind of file like txt, doc , json etc.
File file = await File("${directory.path}/Toastguyz.json").create();
// Read the file content
String fileContent = await file.readAsString();
print("fileContent : ${fileContent}");
}
So for creating a file location I have used methods getExternalStorageDirectory() for android platform and getApplicationSupportDirectory() for ios platform to use recommended File locations for android and ios respectively.
We will use Path_Provider dependency/APIs for accessing file locations. Also, to check whether device platform is android or ios we will use io APIs. File manipulation related features also require io APIs.
import ‘dart:io’;
import ‘package:path_provider/path_provider.dart’;
We have created here a new json file “Toastguyz.json” using File.create() method. Then to read the content of the file we have an async method file.readAsString() which gives us the result of a file content as a String value.
This will give you the expected output as per our requirements.
Write files from your android or ios devices
To write files at your custom android or ios location, you must have a file at that location. So, we will first create a file at some custom location in our android/ios devices and then we will try to write data in to that file.
To access custom file system location we will use a third party package called Path_Provider.
In our main.dart file, I have created a Home class inside which I have added a button to write files at android or ios device locations. Following is the method I have added to write files to custom device locations.
writeFilesToCustomDevicePath() async {
// Retrieve "External Storage Directory" for Android and "NSApplicationSupportDirectory" for iOS
Directory directory = Platform.isAndroid
? await getExternalStorageDirectory()
: await getApplicationSupportDirectory();
// Create a new file. You can create any kind of file like txt, doc , json etc.
File file = await File("${directory.path}/Toastguyz.json").create();
// Convert json object to String data using json.encode() method
String fileContent=json.encode({
"Website": {
"Name": "Toastguyz",
"Description": "Programming Tutorials",
},
});
// You can write to file using writeAsString. This method takes string argument
// To write to text file we can use like file.writeAsString("Toastguyz file content");
return await file.writeAsString(fileContent);
}
So for creating a file location I have used methods getExternalStorageDirectory() for android platform and getApplicationSupportDirectory() for ios platform to use recommended File locations for android and ios respectively.
We will use Path_Provider dependency/APIs for accessing file locations and io APIs to check device platform device and perform File related operations.
import ‘dart:io’;
import ‘package:path_provider/path_provider.dart’;
We have created here a new json file “Toastguyz.json” using File.create() method. Then to write content in file we have an async method file.writeAsString() which takes String argument/parameter to write in to the file.
So to create json object as a String value will use json.encode() method as shown in the method. Then we will pass converted resultant String to our file.writeAsString()
You can also create any doc, txt or other file type and write according content in to it as per your requirements.
Now, we’re done with writing files to custom device location.
Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.