Read and Write a Text File in Flutter

A text file is any file that contains only text data—no formatting, images, or anything else. You can create a text file in your favorite text editor and name it with a “.txt” extension. Text files are often used for storing data like configuration settings, lists of information, and user-generated content.

Text files are an important part of modern computing, and knowing how to read and write them is essential for any developer. There are many reasons why you might need to read and write files in Flutter. You might want to save data locally so that it can be accessed even if the user is offline.

In this post, we’re going to show you how to read and write text files in Flutter.

//read text file in assets folder
Future<String> loadEmojiString(String fileName) async {
  return await rootBundle.loadString('assets/$fileName.txt');
}

//append data to the end of a text file
write(String content) async {
  final directory = await getApplicationDocumentsDirectory();
  final File file = File('${directory.path}/somefile.txt');
  await file.writeAsString(content, mode: FileMode.append);
}

//write/override data to a text file
write(String content) async {
  final directory = await getApplicationDocumentsDirectory();
  final File file = File('${directory.path}/somefile.txt');
  await file.writeAsString(content);
}

Remember to import these packages when workign with text file:

import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close