在某些情况下,您需要读写文件到磁盘。例如,您可能需要在应用重新启动后保留数据,或者从互联网下载数据并将其保存以供以后离线使用。

要在移动或桌面应用中将文件保存到磁盘,请将 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),
      ),
    );
  }
}