flutter如何获取iOS系统储存空间数据

在Flutter开发中,如何获取iOS设备的系统存储空间数据?包括总容量、可用空间和已用空间等。是否有现成的插件或方法可以实现?需要注意哪些平台差异或权限问题?求具体实现方案或代码示例。

2 回复

在Flutter中,使用 path_providerdart:io 获取iOS储存空间。通过 Directory 获取应用目录,再使用 statvfsFileSystemEntity 统计可用和总空间。

更多关于flutter如何获取iOS系统储存空间数据的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中获取iOS系统储存空间数据,可以通过以下方法实现:

1. 使用 path_providerdart:io

首先添加依赖:

dart
dependencies:
  path_provider: ^2.1.1

然后使用以下代码获取储存空间信息:

import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<Map<String, dynamic>> getStorageSpace() async {
  try {
    final directory = await getApplicationDocumentsDirectory();
    final stat = FileStat.statSync(directory.path);
    
    // 获取设备存储信息(iOS需要额外处理)
    final total = await _getTotalDiskSpace();
    final free = await _getFreeDiskSpace();
    final used = total - free;
    
    return {
      'total': total,
      'free': free,
      'used': used,
    };
  } catch (e) {
    throw Exception('获取存储空间失败: $e');
  }
}

// 获取总存储空间(需要平台通道)
Future<int> _getTotalDiskSpace() async {
  if (Platform.isIOS) {
    // iOS需要通过平台通道调用原生API
    final MethodChannel channel = MethodChannel('storage_info');
    final int? total = await channel.invokeMethod('getTotalDiskSpace');
    return total ?? 0;
  }
  return 0;
}

// 获取可用空间
Future<int> _getFreeDiskSpace() async {
  if (Platform.isIOS) {
    final MethodChannel channel = MethodChannel('storage_info');
    final int? free = await channel.invokeMethod('getFreeDiskSpace');
    return free ?? 0;
  }
  return 0;
}

2. iOS原生代码实现

在iOS项目中添加平台通道代码:

Swift代码 (AppDelegate.swift):

import UIKit

public class StorageInfoPlugin: NSObject {
    static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "storage_info", binaryMessenger: registrar.messenger())
        let instance = StorageInfoPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
}

extension StorageInfoPlugin: FlutterPlugin {
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getTotalDiskSpace":
            result(getTotalDiskSpace())
        case "getFreeDiskSpace":
            result(getFreeDiskSpace())
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    private func getTotalDiskSpace() -> Int64 {
        do {
            let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
            let space = (systemAttributes[.systemSize] as? NSNumber)?.int64Value
            return space ?? 0
        } catch {
            return 0
        }
    }
    
    private func getFreeDiskSpace() -> Int64 {
        do {
            let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
            let freeSpace = (systemAttributes[.systemFreeSize] as? NSNumber)?.int64Value
            return freeSpace ?? 0
        } catch {
            return 0
        }
    }
}

3. 注册插件

AppDelegate.swift中注册:

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        StorageInfoPlugin.register(with: registrar(forPlugin: "StorageInfoPlugin")!)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

使用说明:

  • 返回的数据单位是字节(bytes)
  • 可以转换为GB:(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)
  • 需要在iOS项目的Info.plist中添加权限说明

这种方法通过平台通道调用iOS原生API来准确获取存储空间信息,是最可靠的解决方案。

回到顶部