We need to read and write files to disk in an app while handling cases.
Reading and writing files to disk is a way to persist data locally in the app. Data stored in the disk is safe in all stages of the application.
When the user uninstalls the app then the disk data will be cleared otherwise it will keep safe in the disk.
You may also check our Flutter app Development Services page.
In Flutter, To save files to disk, combine the path_provider
plugin with the dart:io
library.
This task uses the following steps to read and write from disk.
- First of all Find the correct path
- Create a reference to the file location
- Write data to the file
- Read data from the file
Let’s start with the implementation
Add dependency
1 |
path_provider: ^2.0.10 |
1. Find the correct local path
This example stores information in the documents directory. You can find the path to the documents directory as follows:
1 2 3 4 5 |
Future<String> get _localPath async { final directory = await getApplicationDocumentsDirectory(); return directory.path; } |
2. Create a reference to the file location
Once you know where to store the file, create a reference to the file’s full location. You can use the File
class from the dart:io
library to achieve this.
1 2 3 4 |
Future<File> get _localFile async { final path = await _localPath; return File('$path/counter.txt'); } |
3. Write data to the file
First, write some data to the file. The counter is an integer, but is written to the file as a string using the '$counter'
syntax.
1 2 3 4 5 6 |
Future<File> writeCounter(int counter) async { final file = await _localFile; // Write the file return file.writeAsString('$counter'); } |
4. Read data from the file
We have some data on disk, we can read it. Once again, use the File
class.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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; } } |
A complete example of read and write from disk
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; void main() { runApp( MaterialApp( debugShowCheckedModeBanner: false, title: 'Reading and Writing File from disk', home: HomePage(storage: IntStorage()), ), ); } class IntStorage { 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 HomePage extends StatefulWidget { const HomePage({ required this.storage}); final IntStorage storage; @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { int count = 0; int savedValue = 0; @override void initState() { super.initState(); widget.storage.readCounter().then((value) { setState(() { savedValue = value; }); }); } Future<File> _incrementCounter() { setState(() { count++; savedValue++; }); // Write the variable as a string to the file. return widget.storage.writeCounter(savedValue); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Reading and Writing Files'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Value in disk $savedValue time${savedValue == 1 ? '' : 's'}.',style: TextStyle(fontSize: 22), ), Text( 'Button tapped $count time${count == 1 ? '' : 's'}.',style: TextStyle(fontSize: 22) ), TextButton(onPressed: (){ setState(() { count = 0; }); }, child: Text("Refresh")) ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } |
Images of the output
Conclusion
In this blog, we have discussed Read and write from disk in the Flutter
I hope it will help you out in understanding and getting a brief idea about it.
You can also go through the FlutterDev for more understanding
Thank you for reading!!