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



By grokonez | July 13, 2018.

Last updated on April 23, 2021.



Related Posts


Got Something To Say:

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

*