flutter
/

Dart File Handling – Read, Write, and Manage Files

Last Sync: Today

On this page

12
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart File Handling – Read, Write, and Manage Files

Introduction to File Handling in Dart

Dart provides the dart:io library for file system operations. Using this library, you can read from and write to files, create directories, list files, and more. File operations are typically asynchronous, ensuring your application remains responsive. This guide covers the essential file handling techniques you'll need in Dart and Flutter applications.

Important Notes

The dart:io library is not available on web platforms. If you're building a Flutter web app, you'll need alternative approaches (like using the browser's file APIs or a server). For command‑line Dart or Flutter for mobile/desktop, dart:io works perfectly.

Reading a File

The simplest way to read a file is using readAsString() or readAsLines(). These methods are asynchronous and return a Future.

DARTRead-only
1
import 'dart:io';

void main() async {
  try {
    // Read entire file as a single string
    String content = await File('example.txt').readAsString();
    print(content);

    // Read as lines (list of strings)
    List<String> lines = await File('example.txt').readAsLines();
    for (var line in lines) {
      print(line);
    }
  } catch (e) {
    print('Error reading file: $e');
  }
}

Reading a File Line by Line (Stream)

For large files, you should read and process them line by line using a Stream. This avoids loading the whole file into memory.

DARTRead-only
1
import 'dart:io';

void main() async {
  var file = File('large_file.txt');
  Stream<String> lines = file.openRead()
      .transform(utf8.decoder)
      .transform(LineSplitter());

  await for (var line in lines) {
    print('Line: $line');
  }
}

Writing to a File

Use writeAsString() to write data to a file. By default, this overwrites the file if it exists. You can use the mode parameter to append instead.

DARTRead-only
1
void main() async {
  var file = File('output.txt');
  await file.writeAsString('Hello, Dart!\n');
  print('File written.');

  // Write with append mode
  await file.writeAsString('Another line\n', mode: FileMode.append);
  print('Appended.');
}

Appending to a File

You can also open the file in append mode and write using a sink, which is more efficient for multiple writes.

DARTRead-only
1
void main() async {
  var file = File('log.txt');
  var sink = file.openWrite(mode: FileMode.append);
  sink.writeln('First entry');
  sink.writeln('Second entry');
  await sink.flush();
  await sink.close();
}

Checking if a File Exists

DARTRead-only
1
void main() async {
  var file = File('data.txt');
  bool exists = await file.exists();
  if (exists) {
    print('File exists');
  } else {
    print('File not found');
  }
}

Deleting a File

DARTRead-only
1
void main() async {
  var file = File('temp.txt');
  if (await file.exists()) {
    await file.delete();
    print('File deleted');
  }
}

Working with Paths

Dart's File class uses system paths. For cross‑platform path handling (like joining directories), you can use the path package (add path: ^1.8.0 to your pubspec.yaml).

DARTRead-only
1
import 'package:path/path.dart' as path;
import 'dart:io';

void main() {
  var directory = Directory.current;
  var filePath = path.join(directory.path, 'data', 'user.txt');
  var file = File(filePath);
  print(file.path);
}

Error Handling

Always handle exceptions when working with files. Common errors include file not found, permission denied, and disk full.

DARTRead-only
1
void main() async {
  try {
    var content = await File('missing.txt').readAsString();
    print(content);
  } on FileSystemException catch (e) {
    print('File error: ${e.message}');
  } catch (e) {
    print('Unexpected error: $e');
  }
}

Working with Directories

You can create, list, and delete directories using the Directory class.

DARTRead-only
1
void main() async {
  var dir = Directory('my_folder');

  // Create directory
  if (!await dir.exists()) {
    await dir.create(recursive: true);
    print('Directory created');
  }

  // List contents
  var contents = await dir.list().toList();
  for (var entity in contents) {
    print(entity.path);
  }

  // Delete directory (must be empty)
  await dir.delete();
}

Key Takeaways

    • Use dart:io for file operations (not available on web).
    • Asynchronous methods (readAsString, writeAsString) are recommended.
    • For large files, process line by line with streams.
    • Always handle exceptions with try/catch.
    • Use the path package for cross‑platform path manipulation.
    • Check file existence before reading to avoid errors.

Try it yourself

// File operations require the dart:io library,
// which is not available in the web environment.
// This example is for local testing.
import 'dart:io';

void main() async {
  var file = File('sample.txt');
  await file.writeAsString('Hello, Dart!\n');
  print(await file.readAsString());
}

Test Your Knowledge

Q1
of 4

Which library provides file handling in Dart?

A
dart:async
B
dart:convert
C
dart:io
D
dart:core
Q2
of 4

What method would you use to read a large file line by line without loading it entirely into memory?

A
readAsString()
B
readAsLines()
C
openRead() + stream transformation
D
File.lineByLine()
Q3
of 4

Which mode allows you to append data to an existing file?

A
FileMode.write
B
FileMode.append
C
FileMode.add
D
FileMode.update
Q4
of 4

How do you check if a file exists?

A
file.exists
B
file.isThere()
C
await file.exists()
D
file.check()

Frequently Asked Questions

Can I use file handling in Flutter web?

No, the dart:io library is not available on the web. For web apps, you need to use browser APIs like dart:html's File class or a package like file_picker to allow user‑selected files, and you cannot write arbitrary files to the user's file system due to security restrictions.

What is the difference between `writeAsString` and `openWrite`?

writeAsString is a one‑shot operation that writes the entire string at once. openWrite returns a IOSink that you can write multiple pieces to and then close; it's more efficient for writing many small pieces.

How do I get the current working directory?

Use Directory.current to get the current working directory as a Directory object. You can then use .path to get its path string.

How do I copy a file?

Use File.copy() method: await source.copy(destinationPath). This asynchronously copies the file and returns a File object for the destination.

What encoding does Dart use for files?

By default, Dart uses UTF‑8 encoding for reading and writing strings. If you need a different encoding, you can use readAsBytes() and write raw bytes, or use a Stream with a custom codec.

Previous

dart json

Next

dart http

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.