Skip to content
CARP Docs
Ask AISystemLightDark
On this page

Sleep sessions

Write a night of sleep with its stages in one call using writeSleepSession.

Copy MarkdownOpen inOpen in GitHubView as MarkdownOpen in Scira AIOpen in ChatGPTOpen in ClaudeOpen in Cursor

writeSleepSession writes a sleep session, such as a night, with its stages in one call. Each stage is a SleepSessionStage: a period of one kind of sleep, such as deep sleep.

On Android, the session is one Health Connect sleep session with its stages, title and notes. HealthKit has no sleep sessions, so on iOS the plugin saves the session as sleep analysis samples; see Stage types.

Signature

Future<bool> writeSleepSession({
  required DateTime startTime,
  required DateTime endTime,
  List<SleepSessionStage> stages = const [],
  String? title,
  String? notes,
  RecordingMethod recordingMethod = RecordingMethod.automatic,
})

writeSleepSession takes these parameters:

ParameterTypeRequiredDefaultDescription
startTimeDateTimeYes—The start of the session. It must be before endTime.
endTimeDateTimeYes—The end of the session
stagesList<SleepSessionStage>Noconst []The stages of the session. See Stage rules.
titleString?No—The title of the session (Android only)
notesString?No—Notes about the session (Android only)
recordingMethodRecordingMethodNoRecordingMethod.automaticHow the session was recorded. On iOS, it must be manual or automatic, and manual marks the samples as entered by the user.

A SleepSessionStage holds one stage:

const SleepSessionStage({
  required HealthDataType type,
  required DateTime startTime,
  required DateTime endTime,
})

SleepSessionStage takes these parameters:

ParameterTypeRequiredDescription
typeHealthDataTypeYesThe kind of sleep. See Stage types.
startTimeDateTimeYesThe start of the stage. It must be before endTime.
endTimeDateTimeYesThe end of the stage

Stage rules

The stages need not cover the whole session. writeSleepSession checks them before anything is written, and throws an ArgumentError unless each stage:

  • has one of the stage types;
  • starts before it ends;
  • lies inside the session;
  • starts at or after the end of the stage before it.

The stages must therefore be sorted by start time and must not overlap. A stage can start exactly where the stage before it ends.

Return value

writeSleepSession returns true when the platform saved the session. It returns false when the platform did not save it, for example without WRITE permission.

On Android, it also returns false once the app has used up its Health Connect write quota. An invalid session throws instead; see Error handling.

Request write permission

All sleep types share one permission on each platform, so request WRITE access to one of them, for example SLEEP_ASLEEP:

final granted = await health.requestAuthorization(
  [HealthDataType.SLEEP_ASLEEP],
  permissions: [HealthDataAccess.WRITE],
);

On Android, declare the sleep permissions in android/app/src/main/AndroidManifest.xml:

android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.health.READ_SLEEP" />
    <uses-permission android:name="android.permission.health.WRITE_SLEEP" />

    <!-- ... the rest of your manifest -->
</manifest>

Writing needs WRITE_SLEEP. Reading the sleep data of other apps, and interval reads, need READ_SLEEP.

Write a night

This sample writes an 8-hour night with six stages:

final bedtime = DateTime(2026, 11, 9, 23, 0);
DateTime at(int minutes) => bedtime.add(Duration(minutes: minutes));

bool saved = await health.writeSleepSession(
  startTime: bedtime,
  endTime: at(480),
  stages: [
    SleepSessionStage(type: HealthDataType.SLEEP_AWAKE_IN_BED, startTime: at(0), endTime: at(20)),
    SleepSessionStage(type: HealthDataType.SLEEP_LIGHT, startTime: at(20), endTime: at(120)),
    SleepSessionStage(type: HealthDataType.SLEEP_DEEP, startTime: at(120), endTime: at(200)),
    SleepSessionStage(type: HealthDataType.SLEEP_REM, startTime: at(200), endTime: at(260)),
    SleepSessionStage(type: HealthDataType.SLEEP_LIGHT, startTime: at(260), endTime: at(470)),
    SleepSessionStage(type: HealthDataType.SLEEP_AWAKE, startTime: at(470), endTime: at(480)),
  ],
  title: 'Night', // stored on Android only, as are notes
);

Stage types

On Android, each stage type maps to a Health Connect stage type. On iOS, the plugin saves in-bed samples for the session, which read as SLEEP_IN_BED, and maps each stage type to a HealthKit sleep analysis value:

Stage typeAndroidiOS
SLEEP_AWAKESTAGE_TYPE_AWAKEawake, read as SLEEP_AWAKE
SLEEP_AWAKE_IN_BEDSTAGE_TYPE_AWAKE_IN_BEDawake, read as SLEEP_AWAKE
SLEEP_ASLEEPSTAGE_TYPE_SLEEPINGasleepUnspecified, read as SLEEP_ASLEEP
SLEEP_LIGHTSTAGE_TYPE_LIGHTasleepCore, read as SLEEP_LIGHT
SLEEP_DEEPSTAGE_TYPE_DEEPasleepDeep, read as SLEEP_DEEP
SLEEP_REMSTAGE_TYPE_REMasleepREM, read as SLEEP_REM
SLEEP_OUT_OF_BEDSTAGE_TYPE_OUT_OF_BEDNo sample. The time is left out of the in-bed samples.
SLEEP_UNKNOWNSTAGE_TYPE_UNKNOWNNo sample. The time stays in bed.

On Android, reads return each stage as its own type. On iOS, the in-bed samples cover the session except its SLEEP_OUT_OF_BED stages. Before iOS 16, HealthKit has no sleep stages: SLEEP_LIGHT, SLEEP_DEEP and SLEEP_REM stages are saved as asleep and read as SLEEP_ASLEEP.

Read a night back

Read the stages with getHealthDataFromTypes. The value of each data point is its duration in minutes:

final points = await health.getHealthDataFromTypes(
  types: [
    HealthDataType.SLEEP_LIGHT,
    HealthDataType.SLEEP_DEEP,
    HealthDataType.SLEEP_REM,
    HealthDataType.SLEEP_AWAKE,
  ],
  startTime: start,
  endTime: end,
);

for (final point in points) {
  final minutes = (point.value as NumericHealthValue).numericValue;
  print('${point.type.name}: $minutes min from ${point.dateFrom}');
}

On Android, SLEEP_SESSION returns the whole session. Reads do not return the title and notes. iOS has no SLEEP_SESSION: read SLEEP_IN_BED for the time in bed.

Reads return a sleep data point when it starts in the range. A stage is returned when the stage starts in the range, whichever session it belongs to. On Android, a SLEEP_SESSION is returned when the session starts in the range.

Reads of consecutive ranges therefore return each data point once. To read a whole night, read up to its end.

On Android, reads also find the stages of sessions that began up to 24 hours before startTime. The stages of one session come together, so the stages of overlapping sessions are not in one time order.

For the minutes of each sleep type per night, see Interval data.

Delete a night

To delete a session, call delete with the session's start as startTime and its end as endTime. What to delete differs per platform:

AndroidiOS

Any sleep type deletes your app's whole sleep sessions in the range, with all their stages:

await health.delete(
  type: HealthDataType.SLEEP_SESSION,
  startTime: start,
  endTime: end,
);

delete removes only your app's samples of the type given, so delete SLEEP_IN_BED and each type that the stages read as:

for (final type in [
  HealthDataType.SLEEP_IN_BED,
  HealthDataType.SLEEP_AWAKE,
  HealthDataType.SLEEP_ASLEEP,
  HealthDataType.SLEEP_LIGHT,
  HealthDataType.SLEEP_DEEP,
  HealthDataType.SLEEP_REM,
]) {
  await health.delete(type: type, startTime: start, endTime: end);
}

For how delete treats the sleep types, see Delete sleep and headache data.

Examples

Write stages from their durations

A sleep tracker that reports how long each stage lasted can lay the stages out one after another from bedtime:

final bedtime = DateTime(2026, 11, 9, 23, 0);
final durations = [
  (HealthDataType.SLEEP_LIGHT, Duration(minutes: 30)),
  (HealthDataType.SLEEP_DEEP, Duration(minutes: 45)),
  (HealthDataType.SLEEP_REM, Duration(minutes: 25)),
  (HealthDataType.SLEEP_AWAKE, Duration(minutes: 5)),
];

// Each stage starts where the one before it ends
var at = bedtime;
final stages = <SleepSessionStage>[];
for (final (type, duration) in durations) {
  stages.add(SleepSessionStage(type: type, startTime: at, endTime: at.add(duration)));
  at = at.add(duration);
}

final saved = await health.writeSleepSession(
  startTime: bedtime,
  endTime: at,
  stages: stages,
  title: 'Sample night', // Android only
);

The session ends where its last stage ends.

Write a nap as one stage

On Android, a session without stages reads only as a SLEEP_SESSION, and on iOS only as SLEEP_IN_BED. To record a nap as sleep, give it one SLEEP_ASLEEP stage that spans it:

await health.writeSleepSession(
  startTime: start,
  endTime: end,
  stages: [
    SleepSessionStage(type: HealthDataType.SLEEP_ASLEEP, startTime: start, endTime: end),
  ],
);

Error handling

writeSleepSession throws for a session it cannot write:

ExceptionWhen
ArgumentErrorstartTime is not before endTime, a stage breaks the stage rules, or on iOS recordingMethod is active or unknown. It is thrown before anything is written.
UnsupportedErrorHealth Connect is not available on the Android device.
PlatformExceptionOn iOS, HealthKit does not accept the session's times: the session is longer than 4 days or ends in the year 4001 or later. Its code is INVALID_ARGUMENT, and it is thrown before anything is saved.

Write methods throw a plain PlatformException, not a HealthPlatformException. To catch it, import package:flutter/services.dart:

try {
  final saved = await health.writeSleepSession(
    startTime: start,
    endTime: end,
    stages: [
      SleepSessionStage(type: HealthDataType.SLEEP_ASLEEP, startTime: start, endTime: end),
    ],
  );
  if (!saved) {
    // Not saved, for example without WRITE permission
  }
} on ArgumentError catch (e) {
  // The session or one of its stages is not valid
  print(e);
} on PlatformException catch (e) {
  // iOS: HealthKit does not accept the session's times
  print(e.code);
}

For the exception types and error codes, see Error handling.

Platform differences

AndroidiOS
  • Health Connect stores one sleep session with its stages, title and notes.
  • Reads return the session as a SLEEP_SESSION data point and each stage as a data point of its type, without the title and notes.
  • delete with any sleep type removes whole sessions with their stages.
  • Each sleep value written with writeHealthData is a session of its own, so write a night with writeSleepSession.
  • HealthKit has no sleep sessions: in one call, the plugin saves in-bed samples and a sample for each stage except out-of-bed and unknown stages.
  • The title and notes are not stored, and there is no SLEEP_SESSION.
  • Before iOS 16, light, deep and REM stages are saved and read as SLEEP_ASLEEP.
  • A session can last at most 4 days.

Quick links

Page · DocumentationCARP DocumentationPage · DocumentationIntroductionPage · DocumentationQuickstartPage · DocumentationTerminologyPage · DocumentationArchitecture