"How much free space is left?" sounds like a question with one answer. On Android it has at least two. The Settings app shows one number for free space. The file system reports another. And the amount your app can really write right now can be different from both, because some blocks are reserved for the system and some of the "free" space is cache that Android can clear.
This matters the moment your app shows a storage figure or decides whether a download fits. Show a number that disagrees with Settings and users think the app is wrong. Check the wrong number before a large write and the write fails halfway.
free_disk_space is a Flutter plugin that reports free, total and usable bytes for internal storage, for any path, and for every Android storage volume: internal shared storage, SD cards and USB drives. Its internal storage figures match what Android Settings shows, and it tells you which number to use for which question.
What it does
Internal storage, as Settings shows it. FreeDiskSpace.internal() returns total, free and usable bytes. On API 26 and later, total and free come from StorageStatsManager with StorageManager.UUID_DEFAULT, which is what the Settings app shows. Below API 26 they come from StatFs on the data directory.
Any path. FreeDiskSpace.forPath(path) returns the same three figures for the file system that holds any absolute path, using StatFs.
Every volume. FreeDiskSpace.volumes() lists every StorageVolume with its UUID, description, primary, removable and emulated flags, mount state, path, and its space where it can be read.
"Does it fit?" FreeDiskSpace.hasSpaceFor(bytes, margin: ..., path: ...) answers the question directly, with an optional safety margin.
Formatting. formatBytes and scaleBytes support SI units (kB, MB, GB, powers of 1000) and IEC units (KiB, MiB, GiB, powers of 1024). Digits and unit labels are pluggable, so you can localise them.
Typed errors. Failures are sealed exceptions: DiskSpaceInvalidPathException, DiskSpacePathNotFoundException, DiskSpaceIoException, DiskSpaceUnsupportedException and DiskSpacePlatformException.
No permissions. The plugin needs none, and queries run on a background thread.
How to use it
Add it from GitHub:
dependencies:
free_disk_space:
git: https://github.com/AbdeldjalilChougui/free_disk_space
Then:
import 'package:free_disk_space/free_disk_space.dart';
Future<void> report() async {
final internal = await FreeDiskSpace.internal();
print('${formatBytes(internal.free)} free of ${formatBytes(internal.total)}');
print('This app can write ${formatBytes(internal.usable, system: ByteUnitSystem.iec)}');
for (final v in await FreeDiskSpace.volumes()) {
final space = v.space;
print('${v.description} (${v.state.name}) at ${v.path}: '
'${space == null ? 'unreadable' : formatBytes(space.free)}');
}
// 700 MB download with a 100 MB safety margin.
if (!await FreeDiskSpace.hasSpaceFor(700000000, margin: 100000000)) {
print('Not enough space');
}
try {
await FreeDiskSpace.forPath('/storage/1234-ABCD');
} on DiskSpacePathNotFoundException catch (e) {
print('SD card missing: ${e.path}');
} on DiskSpaceException catch (e) {
print('Could not read space: $e');
}
}
Which number should I use?
This is the part worth reading twice. For internal storage, the three fields come from different sources and mean different things:
-
totalcomes fromStorageStatsManager.getTotalBytes(API 26+). It is the size as Settings shows it. -
freecomes fromStorageStatsManager.getFreeBytes(API 26+). It is the free space as Settings shows it, and it includes clearable cache. -
usablecomes fromStatFs.getAvailableByteson the data directory. It is what your app can write now.
So the rule is short. To display storage to the user, use total and free, because they agree with Settings. To decide whether a file fits, use usable, or call hasSpaceFor.
For forPath and for non-primary volumes, all three come from StatFs. There, free counts blocks reserved for the system and usable does not.
Localised output
formatBytes prints ASCII digits and standard unit symbols. For anything else, pass your own formatters. The README shows it with package:intl:
final text = formatBytes(
1500000,
numberFormatter: (value, digits) =>
NumberFormat.decimalPatternDigits(locale: 'ar', decimalDigits: digits).format(value),
unitLabeler: (unit) => unit == ByteUnit.megabyte ? 'ميغابايت' : unit.symbol,
);
The formatting helpers are pure Dart, so they work on every platform, even where the storage queries do not.
Migrating from disk_space / disk_space_plus
Those packages return free and total space as a double of megabytes, for internal storage or a path. Here every figure is an int of bytes. Divide by 1000000, or use formatBytes, if you need the old unit.
-
DiskSpace.getFreeDiskSpacebecomes(await FreeDiskSpace.internal()).free. -
DiskSpace.getTotalDiskSpacebecomes(await FreeDiskSpace.internal()).total. -
DiskSpace.getFreeDiskSpaceForPath(p)becomes(await FreeDiskSpace.forPath(p)).free. -
volumes()andhasSpaceFor(...)have no equivalent in the old packages.
One detail: this package's value class is also called DiskSpace. Drop the old import to avoid the name clash.
Things to know
-
Android only. iOS is not supported. On other platforms every call throws
DiskSpaceUnsupportedException. Only the byte formatting helpers work everywhere. -
Volume paths need API 30. Below API 30,
StorageVolume.getDirectory()does not exist, so only the primary volume reports apath, and thereforespace. Secondary volumes reportpath: null. - Below API 24,
volumes()returns only the primary external storage. -
Settings-matching figures need API 26. On older devices
internal()usesStatFs, which reports the partition size rather than the marketed size. -
SD cards and USB drives must be mounted. Their space is read with
StatFs. -
internal()andforPath()differ on purpose. The README gives the numbers from the API 37 emulator:internal()reported the marketed 32 GB and afreeequal to theStatFsusable bytes, whileforPath()of the documents directory reported the 20.96 GB partition and afreeabout 150 MB higher, becauseStatFscounts reserved blocks as free. -
What was tested. The example app has an emulator integration test that compares every figure with
dfon the same device, including an emulated SD card. It ran on the Android Emulator with the Pixel 10 system image, API 37. The README states that it was not yet tested on a physical phone or a USB drive.
Why I built it
The older packages for this return megabytes as a double, for internal storage or one path, and nothing else. That leaves the real questions open. Why does my number differ from Settings? How much can I write, as opposed to how much is "free"? Where is the SD card, and is it mounted? Is there room for this download plus a margin?
Each of those has a precise answer in the Android APIs, but the answers are spread over StorageStatsManager, StorageManager, StorageVolume and StatFs, with different behaviour by API level. I wanted them behind one small Dart API that returns bytes as integers, names the three figures honestly, lists the volumes, and fails with a typed exception when a path is missing instead of returning zero.
The integration test against df exists for the same reason: a storage figure is only useful if you can say where it comes from and check it.
Get the code
The source, the README with the table of sources per field, the example app and its integration test are on GitHub: https://github.com/AbdeldjalilChougui/free_disk_space. It's MIT licensed. Issues and pull requests are welcome, especially results from physical phones, SD cards and USB drives.
Originally published at abdeldjalilchougui.biz.
Top comments (0)