text
stringlengths
1
372
in some cases, you need to read and write files to disk.
for example, you might need to persist data across app launches,
or download data from the internet and save it for later offline use.
to save files to disk on mobile or desktop apps,
combine the path_provider plugin with the dart:io library.
this recipe uses the following steps:
to learn more, watch this package of the week video
on the path_provider package:
info note
this recipe doesn’t work with web apps at this time.
to follow the discussion on this issue,
check out flutter/flutter issue #45296.
<topic_end>
<topic_start>
1. find the correct local path
this example displays a counter. when the counter changes,
write data on disk so you can read it again when the app loads.
where should you store this data?
the path_provider package
provides a platform-agnostic way to access commonly used locations on the
device’s file system. the plugin currently supports access to
two file system locations:
this example stores information in the documents directory.
you can find the path to the documents directory as follows:
<code_start>
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
<code_end>
<topic_end>
<topic_start>
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.
<code_start>
Future<File> get _localFile async {
final path = await _localPath;
return file('$path/counter.txt');
}
<code_end>
<topic_end>
<topic_start>
3. write data to the file
now that you have a file to work with,
use it to read and write data.
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.
<code_start>
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// write the file
return file.writeAsString('$counter');
}
<code_end>
<topic_end>
<topic_start>
4. read data from the file
now that you have some data on disk, you can read it.
once again, use the file class.
<code_start>
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;
}
}
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
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');
}