跳至主要內容

讀寫檔案

在某些情況下,您需要讀取和寫入磁碟上的檔案。例如,您可能需要在應用程式啟動之間保存資料,或從網際網路下載資料並保存以供稍後離線使用。

若要在行動或桌面應用程式上將檔案儲存到磁碟,請將 path_provider 外掛程式與 dart:io 程式庫結合使用。

本食譜使用以下步驟

  1. 找出正確的本地路徑。
  2. 建立檔案位置的參照。
  3. 將資料寫入檔案。
  4. 從檔案讀取資料。

若要瞭解更多資訊,請觀看本週套件關於 path_provider 套件的影片


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. 建立檔案位置的參照

#

一旦知道要儲存檔案的位置,請建立檔案完整位置的參照。您可以使用來自 dart:io 程式庫的 File 類別來完成此操作。

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),
      ),
    );
  }
}