Flutter Read/Write File Example – with path_provider and dart:io

In this tutorial, we’re gonna build a Flutter App that can read file and write data to file for later use. To do this, we need to combine path_provider plugin with dart:io library.

Flutter App Overview

Our Flutter App has a Text field, when we click on Write to File button, the String in Text field will be written to text.txt file (appending text) and display on Screen.

flutter-read-write-file-example-overview

Everytime we launch the App, it read text.txt file and show contents inside.
We can also clear content of the file by Clear Contents button.

Read/Write Files

Find Local Path

We need a place to write data on disk and read it again when the app loads.
>> So we use path_provider plugin to access Documents directory (on iOS, this corresponds to NSDocumentDirectory, on Android, this is the AppData directory).


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

Reference to File

To create a reference to the File full location (in our case, the text.txt file), we use File class from the dart:io library.


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

Write data to File

We will write a string to a file using File writeAsString() method. It returns a Future<File> that completes with this File object once the entire operation has completed.

By default, writeAsString() creates the file and truncates the file if it already exists.
>> To append data to existing file, we pass FileMode.append mode as second parameter.


Future writeFile(String text) async {
  final file = await _localFile;
  return file.writeAsString('$text\r\n', mode: FileMode.append);
}

Read data from File

We use File readAsString() method to read the entire contents as a string. It returns a Future<String> that completes with the string once contents has been read.


Future readFile() async {
  try {
    final file = await _localFile;

    String content = await file.readAsString();
    return content;
  } catch (e) {
    return '';
  }
}

Complete Code


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

void main() {
  runApp(
    MaterialApp(
      title: 'Read/Write Files',
      home: MyApp(storage: TextStorage()),
    ),
  );
}

class TextStorage {
  Future get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

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

  Future readFile() async {
    try {
      final file = await _localFile;

      String content = await file.readAsString();
      return content;
    } catch (e) {
      return '';
    }
  }

  Future writeFile(String text) async {
    final file = await _localFile;
    return file.writeAsString('$text\r\n', mode: FileMode.append);
  }

  Future cleanFile() async {
    final file = await _localFile;
    return file.writeAsString('');
  }
}

class MyApp extends StatefulWidget {
  final TextStorage storage;

  MyApp({Key key, @required this.storage}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
  TextEditingController _textField = new TextEditingController();

  String _content = '';

  @override
  void initState() {
    super.initState();
    widget.storage.readFile().then((String text) {
      setState(() {
        _content = text;
      });
    });
  }

  Future _writeStringToTextFile(String text) async {
    setState(() {
      _content += text + '\r\n';
    });

    return widget.storage.writeFile(text);
  }

  Future _clearContentsInTextFile() async {
    setState(() {
      _content = '';
    });

    return widget.storage.cleanFile();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Read/Write File Example'),
        backgroundColor: Colors.blue,
      ),
      body: Container(
        padding: EdgeInsets.all(20.0),
        child: Column(
          children: [
            TextField(
              controller: _textField,
            ),
            Padding(
              padding: EdgeInsets.all(20.0),
              child: RaisedButton(
                child: Text('Write to File'),
                onPressed: () {
                  if (_textField.text.isNotEmpty) {
                    _writeStringToTextFile(_textField.text);
                    _textField.clear();
                  }
                },
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 20.0),
              child: RaisedButton(
                child: Text(
                  'Clear Contents',
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.redAccent,
                onPressed: () {
                  _clearContentsInTextFile();
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: new SingleChildScrollView(
                child: Text(
                  '$_content',
                  style: TextStyle(
                    color: Colors.blue,
                    fontSize: 22.0,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Source Code

file_example

8 thoughts on “Flutter Read/Write File Example – with path_provider and dart:io”

  1. Hi! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no data backup. Do you have any solutions to protect against hackers?

  2. This is very interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your fantastic post. Also, I have shared your site in my social networks!

  3. After examine a few of the blog posts on your web site now, and I actually like your method of blogging. I bookmarked it to my bookmark web site record and can be checking again soon. Pls take a look at my site as properly and let me know what you think.

  4. I have noticed that in old digital cameras, special sensors help to aim automatically. The sensors involving some cams change in in the area of contrast, while others utilize a beam associated with infra-red (IR) light, particularly in low lighting. Higher standards cameras at times use a combination of both techniques and might have Face Priority AF where the video camera can ‘See’ your face while keeping your focus only in that. Thanks for sharing your opinions on this blog.

  5. I just like the helpful info you supply to your articles. I will bookmark your blog and test once more here frequently. I’m relatively sure I抣l learn many new stuff right here! Good luck for the next!

Leave a Reply

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