Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 339
Suragch Avatar asked Jan 10 '19 06:01

Suragch


People also ask

How do I read a text file in dart?

If you are using a text editor like Visual Studio Code you can use Ctrl+Shift+P and select 'Dart: New Project' to create a project. Now open the project folder in a text editor. I am using Visual Studio Code. import 'dart:io';import 'package:path/path.


2 Answers

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

  • You can also get the path string with join(directory.path, 'my_file.txt') but you need to import 'package:path/path.dart'.
  • Flutter's Official Documentation of Reading and Writing Files
  • This works for iOS, Android, Linux and MacOS but not for web.
like image 111
Suragch Avatar answered Oct 02 '22 09:10

Suragch


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

like image 20
Iván Yoed Avatar answered Oct 02 '22 09:10

Iván Yoed