Using Health Package in Flutter to Read Sleep Data

Ramesh Angamuthu
IceApple Tech Talks
2 min readOct 10, 2023

In flutter, we can use Health Package to access the health and fitness data from google fit and apple health. In this article we can learn to read the sleep data using Health Package.

Step 1: Setup the flutter environment. Follow this link for environment setup. https://docs.flutter.dev/get-started/install. After environment setup, create a new project by running the below command.

flutter create flutter_sleep_demo

Step 2: add the following Flutter package dependency in pubspec.yaml file.

health: ^8.0.0
permission_handler: ^10.2.0

Step 3: add the following line to your AndroidManifest.xml file.

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

Step 4: add the following lines to your Info.plist for iOS

<key>NSHealthShareUsageDescription</key>
<string>We will sync your data with the Apple Health app to give you better insights</string>
<key>NSHealthUpdateUsageDescription</key>
<string>We will sync your data with the Apple Health app to give you better insights</string>

Step 5: add the below code in main.dart file and run the flutter project.

import 'package:flutter/material.dart';
import 'package:health/health.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Health Demo'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

Future<void> getSleepData(BuildContext context) async{
final types = [
HealthDataType.SLEEP_ASLEEP,
HealthDataType.SLEEP_AWAKE
];

final permissions = [
HealthDataAccess.READ,
HealthDataAccess.READ
];
final now = DateTime.now();
final yesterday = now.add(const Duration(days: -10));

HealthFactory health = HealthFactory();

await health.requestAuthorization(types, permissions: permissions);

PermissionStatus activityPermissionStatus = await Permission.activityRecognition.request();

if (Platform.isIOS || activityPermissionStatus == PermissionStatus.granted) {
List<HealthDataPoint> healthData =
await health.getHealthDataFromTypes(yesterday, now, types);
final sleepData = healthData
.where((dataPoint) => dataPoint.type == HealthDataType.SLEEP_ASLEEP);
if (sleepData.isNotEmpty) {
for (var item in sleepData) {
print(item);
}
} else {
print('No sleep data available for the specified day.');
}
}
}


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: () async=>{
await getSleepData(context)
},
child: Container(
decoration: ShapeDecoration(
color: const Color.fromARGB(255, 7, 85, 158),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32),
)),
width: 209,
height: 54,
child: const Center(
child: Text(
"Get Sleep Record",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w300,
letterSpacing: 0.80,
),
),
),
),
)
],
),
)
);
}
}

The app will show Get Sleep Record button, while clicking the button, the app will request for permission. If the platform is android, then it will ask user to login using google account. After successful login, the sleep record will get printed in console.

If the platform is iOS, then iOS will ask the user to provide permission to read the sleep data. On successful permission, the user can view sleep record in the console. This sample will return the record for last 10 days.

Note: iOS will not return the permission status due to security reason. If the user has permission, then the user will get the sleep data, otherwise an empty array will be returned to the user.

--

--