How to Read & Write files in Flutter?

How to Read and Write files In Flutter?

While using Flutter to develop mobile applications, you may want to write files to device storage or read the file in storage. So, in this article, we will see how to read and write files in Flutter. Moreover, we will also see how to obtain the permissions required to perform these tasks.

How to Read and Write files In Flutter?

Dependencies

The first thing to do is to install the dependencies. So, install these dependencies by adding them to pubspec.yaml file. There are two dependencies to be added: path_provider to help us get the directory of the file & simple_permissions for requesting permission.

dependencies:
path_provider: ^0.4.1
simple_permissions: ^0.1.9

Requesting Permission

In Android, to write a file to external storage, the application needs to be granted WRITE_EXTERNAL_STORAGE permission. That permission also grants the application READ_EXTERNAL_STORAGE permission. We also need to add permission in AndroidManifest.xml.

In order to get permission, the application needs to ask the user for each permission by showing a popup. We need to do the same in Flutter. We can use a library such as SimplePermissions. The below example will help you get a better idea.

bool _allowWriteFile = false;

@override
void initState() {
super.initState();
requestWritePermission();
}

// Platform messages are asynchronous, so we initialize in an async method.
requestWritePermission() async {
PermissionStatus permissionStatus = await SimplePermissions.requestPermission(Permission.WriteExternalStorage);

if (permissionStatus == PermissionStatus.authorized) {
setState(() {
_allowWriteFile = true;
});
}
}

Determining the Directory Path

Get the path to the directory where the file is. Usually, a file is in the application’s document directory. It can also be in the application’s cache directory, or in the external storage directory. To get the path easily and reduce the chance of type, use PathProvider class. Consider the below example for better understanding.

Future get _localPath async {
// Application documents directory: /data/user/0/{package_name}/{app_name}
final applicationDirectory = await getApplicationDocumentsDirectory();

// External storage directory: /storage/emulated/0
final externalDirectory = await getExternalStorageDirectory();

// Application temporary directory: /data/user/0/{package_name}/cache
final tempDirectory = await getTemporaryDirectory();

return applicationDirectory.path;
}

Getting the Reference to the File

To get the reference to the file, you can use the following code:

Future get _localFile async {
final path = await _localPath;

return File('$path/file-name.txt');
}

Writing to A File

After getting the file reference, you can directly write to the file. To write the file you can choose writeAsString or writeAsBytes.

Future _writeToFile(String text) async {
if (!_allowWriteFile) {
return null;
}

final file = await _localFile;

// Write the file
File result = await file.writeAsString('$text');
}

Reading A File

You also need to get the file reference to read a file. For that, you can use readAsString, readAsBytes, or readAsLines. 

Future _readFile() async {
   try {
     final file = await _localFile;

     // Read the file
     return await file.readAsString();
     } catch (e) {
     // Return null if we encounter an error 
     return null;
     }
  }

Conclusion:

Thanks for remaining with us till the end of the article. So, in this article, we have been through How to Read and write files In Flutter? We hope you have enjoyed reading this article. Feel free to comment with your suggestions and feedback.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number
our share of the limelight

as seen on