Saving Data in Flutter

Jan 31 2024 · Dart 3, Flutter 3.10, Visual Studio Code

Part 3: Reading & Writing Files

11. Storing a Text File

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Use path & path_provider Next episode: 12. Creating the File List Screen (Part 1)

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

After adding path and path_provider to our project, we are now ready to write our first file to the app. Like we did with SharedPreferences and FlutterSecureStorage, we’ll begin by creating a helper file that will deal with the reading and writing actions for our files.
So in the lib folder of your project, create a new file, and call it file_helper.dart.

Future<String> get _path async { 
    final directory = await getApplicationDocumentsDirectory(); 
    return directory.path; 
  } 
Future<File> getFile(String fileName) async { 
    final path = await _path; 
    return File(p.join(path, fileName)); 
  } 
  Future<File> writeFile(String fileName, String content) async { 
    final localFile = await getFile(fileName); 
    return localFile.writeAsString(content); 
  } 
Future<String> readFile(String fileName) async { 
    try { 
      final localFile = await getFile(fileName); 
      return await localFile.readAsString(); 
    } catch (e) { 
      print('Error reading file: $e'); 
return ''; 
    } 
  }