在某些情况下,您需要读取和写入磁盘文件。例如,您可能需要将数据持久化到应用下次启动时,或者从互联网下载数据并保存以供以后离线使用。

要在移动或桌面应用上将文件保存到磁盘,请将 path_provider 插件与 dart:io 库结合使用。

本示例将采取以下步骤

  1. 找到正确的本地路径。
  2. 创建文件位置引用。
  3. 将数据写入文件。
  4. 从文件读取数据。

要了解更多信息,请观看此关于 path_provider 包的本周软件包视频

在新标签页中在 YouTube 上观看:“path_provider | Flutter 本周软件包”

1. 找到正确的本地路径

#

此示例显示一个计数器。当计数器更改时,将数据写入磁盘,以便在应用加载时可以再次读取。您应该将此数据存储在哪里?

path_provider 包提供了一种平台无关的方式来访问设备文件系统上常用的位置。该插件目前支持访问两个文件系统位置

临时目录
一个系统可以随时清除的临时目录(缓存)。在 iOS 上,这对应于 NSCachesDirectory。在 Android 上,这是 getCacheDir() 返回的值。
文档目录
一个供应用存储只有它才能访问的文件的目录。系统仅在应用被删除时清除此目录。在 iOS 上,这对应于 NSDocumentDirectory。在 Android 上,这是 AppData 目录。

此示例将信息存储在文档目录中。您可以按如下方式查找文档目录的路径

dart
import 'package:path_provider/path_provider.dart';
  // ···
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

2. 创建文件位置引用

#

一旦您知道文件存储位置,就创建一个指向文件完整位置的引用。您可以使用 File 类从 dart:io 库来实现此目的。

dart
Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/counter.txt');
}

3. 将数据写入文件

#

现在您有了可操作的 File,可以使用它来读取和写入数据。首先,向文件写入一些数据。计数器是一个整数,但使用 '$counter' 语法将其作为字符串写入文件。

dart
Future<File> writeCounter(int counter) async {
  final file = await _localFile;

  // Write the file
  return file.writeAsString('$counter');
}

4. 从文件读取数据

#

现在磁盘上有一些数据了,您可以读取它。再次使用 File 类。

dart
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;
  }
}

完整示例

#
dart
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) {
      setState(() {
        _counter = value;
      });
    });
  }

  Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });

    // Write the variable as a string to the file.
    return widget.storage.writeCounter(_counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Reading and Writing Files')),
      body: Center(
        child: Text('Button tapped $_counter time${_counter == 1 ? '' : 's'}.'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}