Flutter Reading and Writing Files

We already know that,  to read and write files to disk. This can be used to persist data across app launches and some times we are downloading  data from the internet and saved it in our laptop/any external device to use it for later offline use when internet is not available.

Adding Dependency package into  your package’s pubspec.yaml file:

Add the below code into pubspec.yaml file

dependencies:

path_provider:

 

Note: After adding this package run get package method to add all dependencies into it

If you don’t add this dependency package it will show package not found exception in your main.dart file

 

Follow below steps to Read and Write Files in Flutter:

 

  • Finding the correct local path
  • Create a reference to the file location
  • Write data to the file
  • Read data from the file

Finding the correct local path:

Now in this example, we are going to display a counter. When the counter changes, we  want to write data on disk so  when the app loads we can read it again.

 

To access commonly used locations on the device’s file system The path_provider plugin provides a platform-agnostic way . The plugin currently supports access to two file system locations :

 

  • Temporary directory: A temporary directory is a (cache) that the system can clear at any time. On iOS, it will be  NSTemporaryDirectory() returns. On Android, we will get  this  value that getCacheDir() returns.

 

  • Documents directory: To store a new app we use a directory for the app to store files that only it can access. The system clears the directory only when the app is deleted. On iOS, this is the directory name NSDocumentDirectory. On Android, it will be AppData directory.

In this example we are  storing information in the documents directory. We have to find the path to the documents directory :

 

 

Future get _localPath async {
final directory = await getApplicationDocumentsDirectory();

return directory.path;
}

Creating a reference to the file location:

If we  know where to store the file, we have to create a reference to the file’s full location. To achieve this we have to use the File class from the dart:io library.

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

Writing data to the file

We already created a File to  read and write data. Now first  we will write some data to the file that we have created above. because  we are using a counter  now we will  store the integer as a String in the file.

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

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

Read data from the file :

Now  we have stored some data on the disk, now we are going  to read it. To do this Once again, we are  using the File class .

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

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

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

Below is the Complete Example code for Reading and Writing Files in Flutter:

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

import 'package:flutter/foundation.dart';
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 get _localPath async {
final directory = await getApplicationDocumentsDirectory();

return directory.path;
}

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

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

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

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

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

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

class FlutterDemo extends StatefulWidget {
final CounterStorage storage;

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

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

class _FlutterDemoState extends State {
int _counter;

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

Future _incrementCounter() async {
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: Text('Reading and Writing Files')),
body: Center(
child: Text(
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Congratulations You Have Learned  Reading and Writing Files In Flutter….!!!

If It Is Helpful Share It With Your Friends….!!!

If You Have Any Query Make A Comment….!!!

Leave a Reply

Categories