Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Files


Share

Dart Files

Programs often need to save data in a file, so the data is still there the next time the program runs.

In Dart, you work with files through the File class from the dart:io library.

To use a file, create a File object with the name (or path) of the file:

import 'dart:io';

final file = File('notes.txt');

Creating the File object does not create the file on the disk.

It is only a way to point to the file.

Note: The examples on this page delete the files they create at the end, so they do not leave files behind.


Write and Read a File

The writeAsStringSync() method writes a string to the file.

If the file does not exist, it is created.

If the file already exists, the old content is replaced.

The readAsStringSync() method reads the whole file and returns it as a string:

Example

import 'dart:io';

void main() {
  final file = File('greeting.txt');
  file.writeAsStringSync('Hello from a file!');

  String content = file.readAsStringSync();
  print(content);

  file.deleteSync();
}
Try it Yourself »

Result:

Hello from a file!

The word Sync at the end of the name means that the method is synchronous: the program waits until the work is done.



Check if a File Exists

The existsSync() method returns true if the file exists.

The deleteSync() method deletes the file:

Example

import 'dart:io';

void main() {
  final file = File('scores.txt');
  print(file.existsSync());

  file.writeAsStringSync('100');
  print(file.existsSync());

  file.deleteSync();
  print(file.existsSync());
}
Try it Yourself »

Result:

false
true
false

It is a good idea to check that a file exists before you read it.


Add to a File and Read Lines

To add text at the end of a file, instead of replacing it, use mode: FileMode.append.

The readAsLinesSync() method reads the file and returns a list with one string for each line:

Example

import 'dart:io';

void main() {
  final file = File('shopping.txt');
  file.writeAsStringSync('Milk\n');
  file.writeAsStringSync('Bread\n', mode: FileMode.append);
  file.writeAsStringSync('Eggs\n', mode: FileMode.append);

  List<String> items = file.readAsLinesSync();
  print(items);
  for (String item in items) {
    print('Buy $item');
  }

  file.deleteSync();
}
Try it Yourself »

Result:

[Milk, Bread, Eggs]
Buy Milk
Buy Bread
Buy Eggs

The \n at the end of each string is a new line.


Async File Methods

Reading and writing a big file can take time.

Each method also has an async version without Sync in its name, which returns a future.

Use them with await, so the rest of the program does not have to stop and wait:

Sync methodAsync method
writeAsStringSync()writeAsString()
readAsStringSync()readAsString()
readAsLinesSync()readAsLines()
existsSync()exists()
deleteSync()delete()

Example

import 'dart:io';

Future<void> main() async {
  final file = File('diary.txt');
  await file.writeAsString('Today I learned about files.');

  bool found = await file.exists();
  print('File exists: $found');

  String text = await file.readAsString();
  print(text);

  await file.delete();
  print('File exists: ${await file.exists()}');
}
Try it Yourself »

Result:

File exists: true
Today I learned about files.
File exists: false

Handle Errors

If you try to read a file that does not exist, Dart throws a FileSystemException.

Use try and catch to handle it:

Example

import 'dart:io';

void main() {
  final file = File('missing.txt');
  try {
    String content = file.readAsStringSync();
    print(content);
  } on FileSystemException {
    print('Could not read the file');
  }
}
Try it Yourself »

Result:

Could not read the file

Note: Like all of dart:io, the File class does not work in Dart programs that run in a web browser.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.