CodeBlanks Logo Icon CodeBlanks

File I/O

Save and load data with dart:io.

File input/output

To save tasks to a file you use the File class from dart:io. import 'dart:io'; is required.

You write with File('tasks.txt').writeAsStringSync(content) and read with .readAsStringSync(). This makes data persistent.

Synchronous methods suit simple command-line programs; asynchronous alternatives are preferred for large files.

A File example

Typical usage: var file = File('tasks.txt'); file.writeAsStringSync('data'); print(file.readAsStringSync());.

Here you first write to the file, then read the same file and print it. writeAsStringSync creates the file (or overwrites it).

To write many values you join them line by line with tasks.map((t) => t.title).join('\n').

Practice Write tasks to a file and read back

Add import 'dart:io';. In main define var tasks = <Task>[Task('Code write'), Task('Test write')];. Create var file = File('tasks.txt');. Write the titles with file.writeAsStringSync(tasks.map((t) => t.title).join('\n'));. Print with print(file.readAsStringSync());.

Starter code

main.dart
import 'dart:io';

abstract class Trackable {
  bool get isDone;
}

class Task implements Trackable {
  final String title;
  bool done;
  Task(this.title, {this.done = false});

  @override
  bool get isDone => done;
}

void main() {
  // create a tasks list, write to a file, read and print
}

Sample solution

main.dart
import 'dart:io';

abstract class Trackable {
  bool get isDone;
}

class Task implements Trackable {
  final String title;
  bool done;
  Task(this.title, {this.done = false});

  @override
  bool get isDone => done;
}

void main() {
  var tasks = <Task>[Task('Code write'), Task('Test write')];
  var file = File('tasks.txt');
  file.writeAsStringSync(tasks.map((t) => t.title).join('\n'));
  print(file.readAsStringSync());
}

Expected output

Code write
Test write

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method writes to a file?

  • print
  • writeAsStringSync Correct answer
  • save
  • toString

Explanation: writeAsStringSync writes a string to a File.

2 dart:io import

Question
import 'dart:____';
Answer
import 'dart:io';

Explanation: dart:io provides the File class.

3 File input/output parts

Term Meaning
import 'dart:io' Import
File(...) File object
writeAsStringSync Writing
readAsStringSync Reading

All lessons in Intermediate