free geoip
52

Read and Write Local Files Using Dart Easily

Handling local file operations is essential for many applications, especially when developing with Dart, whether it’s for command-line tools or…

Handling local file operations is essential for many applications, especially when developing with Dart, whether it’s for command-line tools or Flutter apps. In this guide, you’ll learn how to read and write local files using Dart efficiently, along with complete code examples and proper class structuring. These methods work perfectly for JSON, text files, logs, or configuration files.

read and write local files with Dart

Why File I/O in Dart Matters?

Dart provides powerful libraries like dart:io that allow developers to manage file operations efficiently. File handling is useful for:

  • Saving user data locally
  • Reading configuration files
  • Logging app behavior
  • Managing offline data storage

Required Package

No external package is required. Everything is built-in with dart:io, which works natively for console and desktop environments (not supported in web apps).

Full Code Example: Read and Write File in Dart

The following Dart code demonstrates a clean way to manage file reading and writing operations using separate classes for each responsibility.

file_writer.dart

import 'dart:io';

class FileWriter {
  final String filePath;

  FileWriter(this.filePath);

  Future<void> write(String content) async {
    final file = File(filePath);
    await file.writeAsString(content, mode: FileMode.write);
    print('File written successfully.');
  }
}

file_reader.dart

import 'dart:io';

class FileReader {
  final String filePath;

  FileReader(this.filePath);

  Future<String> read() async {
    final file = File(filePath);
    if (await file.exists()) {
      String contents = await file.readAsString();
      print('File read successfully.');
      return contents;
    } else {
      throw Exception('File not found: $filePath');
    }
  }
}

main.dart

import 'file_reader.dart';
import 'file_writer.dart';

void main() async {
  const path = 'example.txt';
  final writer = FileWriter(path);
  final reader = FileReader(path);

  await writer.write('Hello from Dart!');
  final content = await reader.read();
  print('File Content: $content');
}

đź”— Extra Resources

Want to explore more Dart and Flutter techniques? Visit dart.dev I/O library to learn all built-in methods for file and socket handling.

This Dart local file handling solution is lightweight, easy to manage, and scalable for larger applications. By separating reading and writing logic into classes, the code becomes modular and testable.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *