Data pages
Read large time ranges page by page with bounded memory using getHealthDataPages.
getHealthDataPages reads the data points of one or more types in a time range page by page, as a lazy Stream<HealthDataPage>. Use it instead of getHealthDataFromTypes for large ranges, such as a first sync of months of heart rate data.
getHealthDataFromTypes keeps every point in memory until it returns, and millions of points mean long garbage collection pauses. With getHealthDataPages, you process each page and let it go, and you can stop the read at any time.
Signature
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
types | List<HealthDataType> | Yes | — | Data types to read, one after another, each once |
startTime | DateTime | Yes | — | Start of the time range (inclusive) |
endTime | DateTime | Yes | — | End of the time range (exclusive) |
preferredUnits | Map<HealthDataType, HealthDataUnit>? | No | — | Unit to return each type's values in |
recordingMethodsToFilter | List<RecordingMethod> | No | const [] | Recording methods to leave out. On iOS, only RecordingMethod.manual has an effect. |
pageSize | int? | No | Health.pageSize | Target number of points per platform call, from 1 to 50,000 |
preferredUnits and recordingMethodsToFilter work as in getHealthDataFromTypes. For the units each platform converts to, see Request preferred units.
Return value
getHealthDataPages returns a Stream<HealthDataPage>. The stream is lazy: nothing is read until you listen to it, and the next page is read only when you are ready for it.
The stream reads the data that is stored while it runs. It is not a live stream of new data and not a snapshot: data written during the read may or may not be in it.
Each HealthDataPage has these fields:
| Field | Description |
|---|---|
type | Data type of every point in the page |
points | The points, oldest first and without duplicates |
isLastPageForType | Whether this is the last page of type. Every type ends with exactly one such page, which is empty if the type had no more data. |
readPermissionDenied | Android only. The app has no READ permission for type, so points are only the records it wrote itself. Always false on iOS. |
Types are read one after another, in the order of types, each type once. Every page except the last page of a type holds at least one point.
Read a large range
Read the pages with await for. The loop asks for the next page only after its body has finished. Memory therefore stays bounded as long as you process each page and let it go:
Here, store stands for your app's own storage, such as a database insert.
Cancel a read
Cancel the stream subscription to stop the read. The plugin then makes no further platform call, and cancel completes once the call in flight has returned; its page or error is dropped:
A break out of an await for loop cancels the read the same way.
Set the page size
pageSize is the target number of data points per platform call: 20,000 by default (Health.defaultPageSize) and at most 50,000 (Health.maxPageSize). Bigger pages need fewer Health Connect calls but more memory per call.
Set it for every read of an instance, or for one read:
A value outside 1 to 50,000 throws a RangeError. The constructor and the setter throw it at once, and getHealthDataPages emits it as the stream's error. The plugin reads pageSize when a read starts, so a change applies to the reads that start after it.
Choose where parsing runs
The platform call always runs in the isolate that calls the plugin. Health.isolateMode decides where the reply is decoded and parsed into data points:
| Mode | Decoding and parsing |
|---|---|
HealthIsolateMode.auto | The default. Replies of 64 KiB or more, a few hundred points, are parsed in a short-lived worker isolate, so the UI keeps running. Smaller replies, calls from an isolate other than the root isolate and calls under flutter test are parsed inline. |
HealthIsolateMode.worker | Always in a short-lived worker isolate |
HealthIsolateMode.inline | Always in the calling isolate; no isolate is started |
Pass the mode to the constructor, or change it later:
The mode applies to every read that returns data points, not only to getHealthDataPages. On Android, Health Connect records are converted off the UI thread, and on iOS, HealthKit replies are delivered off it.
In widget tests, testWidgets runs on fake time and never sees work in another isolate finish. auto parses inline under flutter test; with worker, use inline in the test or wrap the read in tester.runAsync.
Reads call the native method getDataPage. A method channel mock written for 13.x, which answers only getData, keeps working: the plugin then reads each type with one getData call.
Read in your own isolate
To keep your own processing of the points off the UI isolate too, call the plugin from your own isolate. Request permissions on the UI isolate first; off the root isolate, auto parses inline:
RootIsolateToken and BackgroundIsolateBinaryMessenger come from package:flutter/services.dart, and Isolate comes from dart:isolate.
Resume a sync
The plugin does not keep track of what you have read. To sync a long range robustly, read it in time windows and record your progress per finished window. After an interruption, read the unfinished window again.
Every read has a fixed cost in Health Connect calls, so prefer windows of a week or a month to windows of a day:
Reads are at-least-once at a window boundary: a point you already stored can come back. Store points with an upsert keyed by type, uuid and dateFrom; on Android, the heart rate samples of one record share its uuid.
A heart rate, speed, power, cycling cadence or skin temperature record that crosses a boundary is split between the two windows. A sleep point comes in the window it starts in, so consecutive windows return it once. On Android, records and sleep sessions that began more than 24 hours before a window are not looked for.
Handle a missing read permission
A missing READ permission is not an error: the read returns only the data the app wrote itself. On Android, every page of such a read has readPermissionDenied set. Without WRITE permission either, the type has one empty last page with the flag.
Check the flag to tell the user that the data is incomplete:
On iOS, the flag is always false, because HealthKit does not tell apps whether the user granted READ access. To request READ access, see Permissions.
Examples
Export a range to a file
Write each point as one line of JSON, and flush the file before the next page:
File comes from dart:io and jsonEncode from dart:convert.
Count the points of each type
Use isLastPageForType to tell when a type is done:
Error handling
An error ends the stream, and the pages already delivered stay valid. The stream emits these errors:
| Error | When |
|---|---|
RangeError | pageSize is not from 1 to 50,000. |
UnsupportedError | Health Connect is not available. The message says why. |
HealthException | A type is not available on the platform or device (HealthErrorCode.notSupported). On Android, a preferred unit is not one that Health Connect converts to (HealthErrorCode.invalidArgument). Both are checked before anything is read. |
HealthPlatformException | Health Connect or HealthKit reports an error, for example HealthErrorCode.rateLimitExceeded. |
With await for, the loop throws the error:
On Android, a read with READ permission fails with HealthErrorCode.permissionDenied in the background without READ_HEALTH_DATA_IN_BACKGROUND. This also happens on a later page of a read that started in the foreground, including a heart rate read of the app's own records. For the error codes, see Error handling.
Platform differences
- Points come in the order of their records' start times. The samples of one heart rate, speed, power, cycling cadence or skin temperature record come together, as do the stages of one sleep session.
- A heart rate page holds at most about
pageSizesamples, but a record is never split, so a long record makes a larger page. The first page also holds the samples in the range of records that began up to 24 hours beforestartTime. - On Android 14 and later, a page that ends among records with the same start time holds all of them.
- Every page costs Health Connect calls, which count against the app's quota. See Health Connect limits.
- Points come oldest first by end time.
readPermissionDeniedis alwaysfalse: a denied read returns only the samples the app saved, without an error.- While the device is locked, the read fails with
HealthErrorCode.deviceLocked. Retry once the device is unlocked. - A type that needs a newer iOS version fails with
HealthErrorCode.notSupported.
Related
- Data points: all points in one list, or only the newest
- Change tracking: changes since your last sync on Android
- Health Connect limits: quotas and what a read costs
- Error handling: error codes and retries