Flutter存储设备信息获取插件flutter_storage_info的使用

发布于 1周前 作者 eggper 来自 Flutter

Flutter Storage Info

A Flutter plugin to retrieve information about device storage.

This plugin provides methods to get information about both internal and external storage space on an Android device.

Usage

To use this plugin, add flutter_storage_info as a dependency in your pubspec.yaml file.

dependencies:
  flutter_storage_info: ^0.0.6

Import the plugin in your Dart code:

import 'package:flutter_storage_info/flutter_storage_info.dart';

Example

Here is a complete example demonstrating how to use the flutter_storage_info plugin to fetch and display storage information.

Main Application

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_storage_info/flutter_storage_info.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Storage Info Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const StorageInfoPage(),
    );
  }
}

class StorageInfoPage extends StatefulWidget {
  const StorageInfoPage({super.key});

  @override
  StorageInfoPageState createState() => StorageInfoPageState();
}

class StorageInfoPageState extends State<StorageInfoPage>
    with SingleTickerProviderStateMixin {
  double _internalStorageFreeSpace = 0.0;
  double _internalStorageUsedSpace = 0.0;
  double _internalStorageTotalSpace = 0.0;
  double _externalStorageFreeSpace = 0.0;
  double _externalStorageUsedSpace = 0.0;
  double _externalStorageTotalSpace = 0.0;

  late Timer _timer;
  late AnimationController _animationController;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _fetchStorageInfo();

    // Set up a timer to refresh storage info every 5 seconds
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      _fetchStorageInfo();
    });

    // Set up animation controller
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 5),
    );

    _animation = Tween<double>(begin: 0, end: 1).animate(_animationController)
      ..addListener(() {
        setState(() {});
      });

    _animationController.forward();
  }

  @override
  void dispose() {
    _timer.cancel(); // Cancel the timer to prevent memory leaks
    _animationController.dispose();
    super.dispose();
  }

  Future<void> _fetchStorageInfo() async {
    try {
      // Internal Storage Info
      _internalStorageFreeSpace =
          (await FlutterStorageInfo.storageFreeSpace) / (1024 * 1024 * 1024);
      _internalStorageUsedSpace =
          (await FlutterStorageInfo.storageUsedSpace) / (1024 * 1024 * 1024);
      _internalStorageTotalSpace =
          (await FlutterStorageInfo.storageTotalSpace) / (1024 * 1024 * 1024);

      // External Storage Info
      _externalStorageFreeSpace =
          (await FlutterStorageInfo.externalStorageFreeSpace) / (1024 * 1024 * 1024);
      _externalStorageUsedSpace =
          (await FlutterStorageInfo.externalStorageUsedSpace) / (1024 * 1024 * 1024);
      _externalStorageTotalSpace =
          (await FlutterStorageInfo.externalStorageTotalSpace) / (1024 * 1024 * 1024);

      // Update the UI with the new data
      setState(() {});
    } catch (e) {
      debugPrint("Error fetching storage info: $e");
    }
  }

  String _formatSpace(double space) {
    if (space < 1) {
      return "${(space * 1024).toStringAsFixed(2)} MB";
    } else {
      return "${space.toStringAsFixed(2)} GB";
    }
  }

  Color _getSpaceColor(double freeSpace) {
    if (freeSpace > 10) {
      return Colors.green;
    } else if (freeSpace > 5) {
      return Colors.orange;
    } else {
      return Colors.red;
    }
  }

  Widget _buildStorageSection({
    required String title,
    required double freeSpace,
    required double usedSpace,
    required double totalSpace,
  }) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          title,
          style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 15),
        CircularProgressIndicator(
          value: totalSpace > 0 ? usedSpace / totalSpace * _animation.value : 0,
          valueColor: AlwaysStoppedAnimation<Color>(_getSpaceColor(freeSpace)),
          backgroundColor: Colors.grey[300],
          strokeWidth: 15,
        ),
        const SizedBox(height: 10),
        Text(
          'Free: ${_formatSpace(freeSpace * _animation.value)}',
          style: TextStyle(
            color: _getSpaceColor(freeSpace),
            fontSize: 18,
          ),
        ),
        Text(
          'Used: ${_formatSpace(usedSpace * _animation.value)}',
          style: const TextStyle(fontSize: 18),
        ),
        Text(
          'Total: ${_formatSpace(totalSpace * _animation.value)}',
          style: const TextStyle(fontSize: 18),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Flutter Storage Info',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
        centerTitle: true,
        backgroundColor: const Color(0xFF292F2F),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildStorageSection(
                  title: 'Internal Storage',
                  freeSpace: _internalStorageFreeSpace,
                  usedSpace: _internalStorageUsedSpace,
                  totalSpace: _internalStorageTotalSpace,
                ),
                const SizedBox(height: 30),
                _buildStorageSection(
                  title: 'External Storage',
                  freeSpace: _externalStorageFreeSpace,
                  usedSpace: _externalStorageUsedSpace,
                  totalSpace: _externalStorageTotalSpace,
                ),
                const SizedBox(height: 30),
                ElevatedButton(
                  onPressed: () {
                    _fetchStorageInfo();
                    _animationController.reset();
                    _animationController.forward();
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey[100],
                    padding: const EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 10,
                    ),
                  ),
                  child: Visibility(
                    visible: _animationController.status != AnimationStatus.completed,
                    replacement: const Text('Refresh'),
                    child: const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Methods

The following methods are provided by the FlutterStorageInfo class:

Internal Storage (Device Storage)

  • storageFreeSpace: Retrieves the amount of free space available on the device’s internal storage in bytes.
  • storageTotalSpace: Retrieves the total amount of space available on the device’s internal storage in bytes.
  • storageUsedSpace: Retrieves the amount of used space on the device’s internal storage in bytes.

External Storage (SD Card)

  • externalStorageFreeSpace: Retrieves the amount of free space available on the device’s external storage in bytes.
  • externalStorageTotalSpace: Retrieves the total amount of space available on the device’s external storage in bytes.
  • externalStorageUsedSpace: Retrieves the amount of used space on the device’s external storage in bytes.

Conversion Methods

  • getStorageSpaceInMB(String method): Retrieves the specified storage space in megabytes (MB).
  • getStorageSpaceInGB(String method): Retrieves the specified storage space in gigabytes (GB).

Directory Size

  • getSizeOfDirectoryInMB(String directory): Retrieves the size of the specified directory in megabytes (MB).

Storage Type Detection

  • getStorageTypeFromPath(String path): Determines whether the specified path corresponds to internal or external storage. Returns a DeviceStorageType enum value (internal or external).

Storage Usage Calculation

  • calculateStorageUsage(double storageUsed, double storageTotal): Calculates the storage usage value as a ratio (storageUsed / storageTotal). Throws an exception if storageTotal is less than or equal to zero.

Low Storage Detection

  • isLowOnStorage(DeviceStorageType storageType, {double threshold = 0.98}): Checks if the storage usage exceeds the specified threshold (default is 98%). Returns true if usage is above the threshold, otherwise false.

Examples

Get the size of a directory in MB

String directoryPath = '/storage/emulated/0/Movies/MyFolder';
double directorySize = await FlutterStorageInfo.getSizeOfDirectoryInMB(directoryPath);
print('Directory Size: $directorySize MB');

Determine the storage type from a path

String path = '/storage/emulated/0/Android';
DeviceStorageType storageType = FlutterStorageInfo.getStorageTypeFromPath(path);
print('Storage Type: $storageType');

Calculate storage usage value

double storageTotal = await FlutterStorageInfo.getStorageSpaceInGB('getStorageTotalSpaceInGB');
double storageUsed = await FlutterStorageInfo.getStorageSpaceInGB('getStorageUsedSpaceInGB');

double usageValue = FlutterStorageInfo.calculateStorageUsage(storageUsed, storageTotal);
print('Storage Usage Value: $usageValue');

Check if storage is low

DeviceStorageType storageType = DeviceStorageType.internal;
double threshold = 0.95;

bool isLow = await FlutterStorageInfo.isLowOnStorage(storageType, threshold: threshold);
print('Is Low on Storage: $isLow');

Screenshot

Screenshot

Permissions

Android

Add the following permissions to your AndroidManifest.xml file:

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
          package="com.example.app">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

</manifest>

Supported Platforms

  • Android (✅)
  • iOS (🕑)
  • Linux (❌)
  • macOS (❌)
  • Windows (❌)

Issues and Feedback

Please file issues to send feedback or report a bug. Thank you!


更多关于Flutter存储设备信息获取插件flutter_storage_info的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter存储设备信息获取插件flutter_storage_info的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_storage_info插件来获取设备存储信息的代码示例。

首先,确保你已经在pubspec.yaml文件中添加了flutter_storage_info依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_storage_info: ^1.0.0  # 请检查最新版本号

然后,运行flutter pub get来安装依赖。

接下来,你可以在你的Dart文件中使用flutter_storage_info插件。以下是一个完整的示例代码,展示了如何获取设备的存储信息:

import 'package:flutter/material.dart';
import 'package:flutter_storage_info/flutter_storage_info.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  StorageInfo? _storageInfo;

  @override
  void initState() {
    super.initState();
    _getStorageInfo();
  }

  Future<void> _getStorageInfo() async {
    try {
      StorageInfo storageInfo = await StorageInfo.instance;
      List<StorageDirectory> directories = await storageInfo.getDirectories();

      // 打印所有存储目录信息
      directories.forEach((directory) {
        print('Directory: ${directory.path}');
        print('  Is Root: ${directory.isRoot}');
        print('  Description: ${directory.description}');
      });

      // 获取并打印总存储空间和可用存储空间
      StorageUsage usage = await storageInfo.getStorageUsage(directories.first.path);
      print('Total Space: ${usage.totalBytes}');
      print('Used Space: ${usage.usedBytes}');
      print('Free Space: ${usage.freeBytes}');

      // 更新状态
      setState(() {
        _storageInfo = storageInfo;
      });
    } catch (e) {
      print('Error getting storage info: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Device Storage Info'),
        ),
        body: _storageInfo == null
            ? Center(child: CircularProgressIndicator())
            : ListView(
                children: <Widget>[
                  // 这里可以根据需要显示存储信息
                  ListTile(
                    title: Text('Total Space'),
                    subtitle: Text('$_storageInfo!.totalSpace'), // 注意:这里需要根据实际获取的字段调整
                  ),
                  ListTile(
                    title: Text('Used Space'),
                    subtitle: Text('$_storageInfo!.usedSpace'), // 注意:这里需要根据实际获取的字段调整
                  ),
                  ListTile(
                    title: Text('Free Space'),
                    subtitle: Text('$_storageInfo!.freeSpace'), // 注意:这里需要根据实际获取的字段调整
                  ),
                ],
              ),
      ),
    );
  }
}

注意

  1. flutter_storage_info插件的API可能会随着版本更新而变化,请查阅最新的官方文档以确保使用正确的API。
  2. 在上面的示例代码中,_storageInfo!.totalSpace, _storageInfo!.usedSpace, 和 _storageInfo!.freeSpace 是示例字段,实际使用中需要根据插件提供的API获取正确的字段值。例如,可能需要通过StorageUsage对象获取总空间、已用空间和可用空间。
  3. 由于Flutter和插件的API可能会更新,上述代码可能需要根据最新的API进行调整。

这个示例展示了如何在Flutter应用中获取设备的存储信息,并在UI中显示这些信息。你可以根据实际需求进一步扩展和修改这个示例。

回到顶部