text
stringlengths
1
474
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>import 'package:path_provider/path_provider.dart';
// ···
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');
}
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 FlutterDemo extends StatefulWidget {
const FlutterDemo({super.key, required this.storage});
final CounterStorage storage;
@override
State<FlutterDemo> createState() => _FlutterDemoState();
}
class _FlutterDemoState extends State<FlutterDemo> {
int _counter = 0;
@override
void initState() {
super.initState();
widget.storage.readCounter().then((value) {