本指南介绍如何使用PathProvider 插件和Dart的IO库在Flutter中读写文件 。

介绍

PathProvider 插件提供了一种平台透明的方式来访问设备文件系统上的常用位置。该类当前支持访问两个文件系统位置:

  • 临时目录: 系统可随时清除的临时目录(缓存)。在iOS上,这对应于NSTemporaryDirectory() 返回的值。在Android上,这是getCacheDir())返回的值。
  • 文档目录: 应用程序的目录,用于存储只有自己可以访问的文件。只有当应用程序被卸载时,系统才会清除该目录。在iOS上,这对应于NSDocumentDirectory。在Android上,这是AppData目录。

一旦你的Flutter应用程序有一个文件位置的引用,你可以使用dart:ioAPI来执行对文件系统的读/写操作。有关使用Dart处理文件和目录的更多信息,请参阅此概述 和这些示例

读写文件的示例

以下示例展示了如何统计应用程序中按钮被点击的次数(关闭重启数据不丢失):

  1. 通过 flutter create 或在IntelliJ中 File > New Project 创建一个新Flutter App.

  2. pubspec.yaml文件中声明依赖 PathProvider 插件

  3. 用一下代码替换 lib/main.dart中的:

  1. import 'dart:io';
  2. import 'dart:async';
  3. import 'package:flutter/material.dart';
  4. import 'package:path_provider/path_provider.dart';
  5. void main() {
  6. runApp(
  7. new MaterialApp(
  8. title: 'Flutter Demo',
  9. theme: new ThemeData(primarySwatch: Colors.blue),
  10. home: new FlutterDemo(),
  11. ),
  12. );
  13. }
  14. class FlutterDemo extends StatefulWidget {
  15. FlutterDemo({Key key}) : super(key: key);
  16. @override
  17. _FlutterDemoState createState() => new _FlutterDemoState();
  18. }
  19. class _FlutterDemoState extends State<FlutterDemo> {
  20. int _counter;
  21. @override
  22. void initState() {
  23. super.initState();
  24. _readCounter().then((int value) {
  25. setState(() {
  26. _counter = value;
  27. });
  28. });
  29. }
  30. Future<File> _getLocalFile() async {
  31. // get the path to the document directory.
  32. String dir = (await getApplicationDocumentsDirectory()).path;
  33. return new File('$dir/counter.txt');
  34. }
  35. Future<int> _readCounter() async {
  36. try {
  37. File file = await _getLocalFile();
  38. // read the variable as a string from the file.
  39. String contents = await file.readAsString();
  40. return int.parse(contents);
  41. } on FileSystemException {
  42. return 0;
  43. }
  44. }
  45. Future<Null> _incrementCounter() async {
  46. setState(() {
  47. _counter++;
  48. });
  49. // write the variable as a string to the file
  50. await (await _getLocalFile()).writeAsString('$_counter');
  51. }
  52. @override
  53. Widget build(BuildContext context) {
  54. return new Scaffold(
  55. appBar: new AppBar(title: new Text('Flutter Demo')),
  56. body: new Center(
  57. child: new Text('Button tapped $_counter time${
  58. _counter == 1 ? '' : 's'
  59. }.'),
  60. ),
  61. floatingActionButton: new FloatingActionButton(
  62. onPressed: _incrementCounter,
  63. tooltip: 'Increment',
  64. child: new Icon(Icons.add),
  65. ),
  66. );
  67. }
  68. }