The Dart IO library includes classes related to file reading and writing, and it is part of the Dart syntax standard. Therefore, whether it's a script running under Dart VM or Flutter, file operations are performed through the Dart IO library. However, there is an important difference between Dart VM and Flutter: the file system paths. Dart VM runs on PC or server operating systems, while Flutter runs on mobile operating systems, leading to some differences in their file systems.
APP Directory
The application storage directories for Android and iOS are different. The PathProvider plugin provides a platform-agnostic way to access common locations on the device's file system. This class currently supports access to two file system locations:
Temporary Directory: You can use
getTemporaryDirectory()
to obtain the temporary directory, where files may be cleared by the system at any time. On iOS, this corresponds to the value returned byNSTemporaryDirectory()
. On Android, it corresponds to the value returned bygetCacheDir()
.Documents Directory: You can use
getApplicationDocumentsDirectory()
to obtain the application's documents directory, used to store files that only the app can access. The system only clears this directory when the application is uninstalled. On iOS, this corresponds toNSDocumentDirectory
, and on Android, it corresponds to the AppData directory.External Storage Directory: You can use
getExternalStorageDirectory()
to obtain the external storage directory, such as an SD card. Since iOS does not support external directories, calling this method on iOS will throw anUnsupportedError
exception. On Android, it returns the value ofgetExternalStorageDirectory
in the Android SDK.
Once your Flutter application has a reference to a file location, you can use the dart:io
API to perform read/write operations on the file system. For detailed information on handling files and directories in Dart, refer to the Dart language documentation. Below is a simple example.
Example
Using a counter as an example, we can implement the ability to restore click counts after the app restarts. Here, we will use a file to save the data:
Import the PathProvider plugin; add the following declaration in the pubspec.yaml
file:
path_provider: ^2.0.2
After adding it, run flutter packages get
to retrieve the package. The version number may change over time, so readers can use the latest version.
Implementation:
import 'dart:io'; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; class FileOperationRoute extends StatefulWidget { FileOperationRoute({Key? key}) : super(key: key); @override _FileOperationRouteState createState() => _FileOperationRouteState(); } class _FileOperationRouteState extends State<FileOperationRoute> { int _counter = 0; @override void initState() { super.initState(); // Read click count from file _readCounter().then((int value) { setState(() { _counter = value; }); }); } Future<File> _getLocalFile() async { // Get application directory String dir = (await getApplicationDocumentsDirectory()).path; return File('$dir/counter.txt'); } Future<int> _readCounter() async { try { File file = await _getLocalFile(); // Read click count (as a string) String contents = await file.readAsString(); return int.parse(contents); } on FileSystemException { return 0; } } _incrementCounter() async { setState(() { _counter++; }); // Write click count as a string to the file await (await _getLocalFile()).writeAsString('$_counter'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('File Operations')), body: Center( child: Text('Clicked $_counter times'), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } }
The code above is quite simple and does not need further elaboration. It is important to note that this example is solely for demonstrating file reading and writing. In actual development, if you need to store simple data, using the shared_preferences
plugin would be simpler.