Suragch
Suragch

Reputation: 511646

How to read and write a text file in Flutter

How do you read text from a file and write text to a file?

I've been learning about how to read and write text to and from a file. I found another question about reading from assets, but that is not the same. I will add my answer below from what I learned from the documentation.

Upvotes: 45

Views: 78383

Answers (4)

Sagar
Sagar

Reputation: 23

@Suragch 's answer is right. Except the version of path_provider that you want to use now is:

path_provider: ^2.0.9

Upvotes: 0

Shashidhar Yamsani
Shashidhar Yamsani

Reputation: 573

An another way to pull the file from the device is by using adb pull command. You can find the file path by debugging the code and then use adb pull command. adb is located in Android SDK -> platform-tools directory.

./adb pull /storage/emulated/0/Android/data/com.innovate.storage.storage_sample/files/sample.txt ~/Downloads

Upvotes: 0

Ivan Yoed
Ivan Yoed

Reputation: 4395

As additional info to @Suragch's answer, if you want to find the file you created, you can do as the images show:

enter image description here

And then inside that data folder, go again to a folder named data and search for your package, and then go to:

enter image description here

If you happen to create new files, in order to be able to see them, just right click and click Synchronize.

enter image description here

Upvotes: 6

Suragch
Suragch

Reputation: 511646

Setup

Add the following plugin in pubspec.yaml:

dependencies:
  path_provider: ^1.6.27

Update the version number to whatever is current.

And import it in your code.

import 'package:path_provider/path_provider.dart';

You also have to import dart:io to use the File class.

import 'dart:io';

Writing to a text file

_write(String text) async {
  final Directory directory = await getApplicationDocumentsDirectory();
  final File file = File('${directory.path}/my_file.txt');
  await file.writeAsString(text);
}

Reading from a text file

Future<String> _read() async {
  String text;
  try {
    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/my_file.txt');
    text = await file.readAsString();
  } catch (e) {
    print("Couldn't read file");
  }
  return text;
}

Notes

Upvotes: 78

Related Questions