How To Read And Write Files In Flutter

Almost all apps can read and write files into the device’s storage, from desktop apps to mobile apps. That is why today we are going to learn how to read and write files in Flutter, as this is foundational to our learning on this Flutter journey. You may need to read and write files to disk in some circumstances. You may need to persist data across app starts, or you may need to download data from the internet and preserve it for later offline use. Let’s get started!


Setting Up The Directory

Accordingly, the path provider package provides a platform-independent method of accessing frequently used locations on the device’s file system. The plugin now supports two file system locations: Documents and Temporary DATABASE, which correspond to the NSDocument and AppData directories on iOS. Consequently, we need to find a directory where we can read and write files. This example stores information in the documents directory. You can find the path to the documents directory as follows:

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Create a reference to the file’s full location once you’ve decided where to save it. To accomplish this, use the File class from the dart:io library.

Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/counter.txt');
}

Read and Write In Flutter

For this purpose, we finally reach our focal point, which is to read and write files in Flutter, which will be shown below. Follow me.

Additionally, Now that you have a File, you may now read and write data to it. To begin with, write some data to the file. Although the counter is an integer, it is written to the file as a string with the '$counter' syntax.

Future<File> writeCounter(int counter) async {
  final file = await _localFile;

  // Write the file
  return file.writeAsString('$counter');
}

Lastly, you can now read the data that has been saved to disk. Use the File class once more. which the code is shown below.

Future<int> readCounter() async {
  try {
    final file = await _localFile;

    // Read the file
    final contents = await file.readAsString();

    return int.parse(contents);
  } catch (e) {
    // If encountering an error, return 0
    return 0;
  }
}

Full App Read and Write Application

Now that you understand how to read and write, you can use it in your own app to access, read, and write files on the device. You may also check out the full app example below, where it utilizes all that we learned today.

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

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

void main() {
  runApp(
    MaterialApp(
      title: 'Reading and Writing Files',
      home: FlutterDemo(storage: CounterStorage()),
    ),
  );
}

class CounterStorage {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/counter.txt');
  }

  Future<int> readCounter() async {
    try {
      final file = await _localFile;

      // Read the file
      final contents = await file.readAsString();

      return int.parse(contents);
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
  }

  Future<File> writeCounter(int counter) async {
    final file = await _localFile;

    // Write the file
    return file.writeAsString('$counter');
  }
}

class FlutterDemo extends StatefulWidget {
  const FlutterDemo({super.key, required this.storage});

  final CounterStorage storage;

  @override
  State<FlutterDemo> createState() => _FlutterDemoState();
}

class _FlutterDemoState extends State<FlutterDemo> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    widget.storage.readCounter().then((value) {
      setState(() {
        _counter = value;
      });
    });
  }

  Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });

    // Write the variable as a string to the file.
    return widget.storage.writeCounter(_counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Reading and Writing Files'),
      ),
      body: Center(
        child: Text(
          'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

Conclusion

To conclude, we learned how to read and write files in Flutter since it is fundamental to our learning on this Flutter journey. The path provider package provides a platform-independent way of accessing frequently used file system locations on the device. If you find this blog outdated in the future, you can always check the official documentation. If you found it useful, please share it. Thank you! This is Louie Jay Lomibao signing out.

Leave a Comment

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