Skip to content
tezvyn:
Menu

Reading and Writing Files in Dart

Source: api.dart.devEasyHow cards are made

Treat files as either a single string for simple cases or a stream of data for large ones. Use dart:io for saving user settings or processing logs. The main footgun is using synchronous methods like readAsStringSync, which can freeze your app.

Why it exists

Apps often need to persist data beyond their runtime—saving user preferences, caching data, or logging events. The dart:io library provides a standard, cross-platform API to interact with the file system directly, making these tasks possible in Dart and Flutter.

The mental model

Think of a File object not as the file itself, but as a remote control for a file on your disk. You create this remote by giving it a path (File('my_data.txt')). Then, you use its buttons—methods like readAsString() or writeAsString()—to perform operations on the actual file.

How it works

The File class offers two main approaches for I/O operations. First, convenience methods like readAsString() or writeAsString('content'). These are great for small configuration files and return a Future, so you must await the result. Second, streams. For large files, use openRead() to get a Stream of bytes or openWrite() to get an IOSink. Streams prevent loading a huge file into memory all at once and allow you to process data in chunks.

When to use it

Use convenience methods like readAsString() for small, simple files, like a user's theme preference in a JSON file. Use streams (openRead()) when dealing with files of unknown or potentially large size, like user-uploaded videos or extensive log files. This prevents your app from crashing due to high memory usage.

When not to use it

Avoid using the synchronous versions of methods (e.g., readAsStringSync()) in any performance-critical code, especially in a Flutter app's UI thread. They block all other operations until the file I/O is complete, leading to a frozen UI. For simple key-value storage, a package like shared_preferences might be a simpler abstraction than direct file I/O.

One canonical example

To write text to a file and then read it back, you can use the asynchronous convenience methods. This pattern is common for saving and loading simple state. import 'dart:io'; void main() async { final file = File('log.txt'); // Write to the file

await file.writeAsString('Hello, Dart!');

// Read from the file

if (await file.exists()) {

final contents = await file.readAsString(); print(contents); // Prints "Hello, Dart!" } } This example first creates a File object, writes a string to it, and then reads the entire content back. Each operation is asynchronous and uses await.

Interview question

Which scenario best justifies using a synchronous file I/O method like readAsStringSync() in Dart?

  • a.To avoid async/await and simplify code logic for file operations.
  • b.When reading a small configuration file to quickly load settings.
  • c.In a command-line utility where blocking the main thread is acceptable.Correct
  • d.When processing large log files to ensure data integrity during writes.
Why?

Synchronous methods block the thread, which is detrimental in UI applications. However, in non-UI contexts like simple command-line utilities, where blocking the main thread does not impact user experience, their use can be acceptable. Even for small files (Option B), asynchronous methods are generally preferred to keep the application responsive.

Just read this? Test yourself on what you have been reading.

Read the original → api.dart.dev

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on dart — each one lists the topics its interview covers.

See open roles