<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yogx Technologies on Medium]]></title>
        <description><![CDATA[Stories by Yogx Technologies on Medium]]></description>
        <link>https://medium.com/@yogxworld_96212?source=rss-a5a5b9b154da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n3CJRaA3BpjKhK5HBkIiyQ.png</url>
            <title>Stories by Yogx Technologies on Medium</title>
            <link>https://medium.com/@yogxworld_96212?source=rss-a5a5b9b154da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:28:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yogxworld_96212/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Streams, Listen & StreamSubscription in Advanced Flutter]]></title>
            <link>https://medium.com/@yogxworld_96212/streams-listen-streamsubscription-in-advanced-flutter-5ed99269fcb7?source=rss-a5a5b9b154da------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed99269fcb7</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[liste]]></category>
            <category><![CDATA[streamsubscription]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Yogx Technologies]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 11:39:58 GMT</pubDate>
            <atom:updated>2026-08-09T11:39:58.997Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re working with Flutter, sooner or later you’ll encounter <strong>Streams</strong>.</p><p>Streams are one of the most useful concepts in Dart for handling data that arrives <strong>asynchronously over time</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqvr3Bz_sMmGOi40YdAQUQ.jpeg" /><figcaption>Streams, Listen &amp; StreamSubscription in Advanced Flutter</figcaption></figure><p>Examples include:</p><ul><li>Internet connectivity changes</li><li>Firebase real-time data</li><li>WebSocket messages</li><li>Location updates</li><li>Authentication state changes</li><li>Database changes</li><li>Device sensors</li><li>Timers</li><li>User events</li><li>Real-time APIs</li></ul><p>In this article, we’ll understand:</p><ol><li>What is a Stream?</li><li>What is listen()?</li><li>What is StreamSubscription?</li><li>Why do we need StreamSubscription?</li><li>How to cancel a subscription</li><li>StreamController</li><li>Real-world Flutter examples</li><li>Using Streams with BLoC</li><li>Common mistakes</li><li>When should you use Streams?</li></ol><h3>1. What is a Stream in Dart?</h3><p>A Stream represents a sequence of asynchronous events or data.</p><p>Unlike a normal variable that contains a single value, a Stream can continuously provide values over time.</p><p>Think about it like a <strong>water pipe</strong>.</p><pre>Stream<br>            │<br>            ▼<br>      ┌─────────────┐<br>      │   Event 1   │<br>      ├─────────────┤<br>      │   Event 2   │<br>      ├─────────────┤<br>      │   Event 3   │<br>      ├─────────────┤<br>      │   Event 4   │<br>      └─────────────┘</pre><p>The data doesn’t necessarily arrive all at once.</p><p>For example:</p><pre>10:00:01 → Connected<br>10:00:05 → Disconnected<br>10:00:08 → Connected<br>10:00:12 → Disconnected</pre><p>A Stream allows us to react to these events as they happen.</p><h3>2. Creating a Simple Stream</h3><p>Dart provides several ways to create Streams.</p><p>For example:</p><pre>Stream&lt;int&gt; numberStream() async* {<br>  for (int i = 1; i &lt;= 5; i++) {<br>    await Future.delayed(<br>      const Duration(seconds: 1),<br>    );</pre><pre>    yield i;<br>  }<br>}</pre><p>This Stream produces:</p><pre>1<br>2<br>3<br>4<br>5</pre><p>with a one-second delay between each value.</p><p>The yield keyword sends a value into the Stream.</p><h3>3. What is listen()?</h3><p>Creating a Stream isn’t enough.</p><p>We need something that receives the data coming from the Stream.</p><p>That’s where:</p><pre>listen()</pre><p>comes in.</p><p>Example:</p><pre>numberStream().listen((value) {<br>  print(value);<br>});</pre><p>Output:</p><pre>1<br>2<br>3<br>4<br>5</pre><p>Every time the Stream emits a value, the callback inside listen() is executed.</p><p>You can think of it as:</p><pre>Stream<br>  │<br>  │ emits data<br>  ▼<br>listen()<br>  │<br>  ▼<br>Callback</pre><h3>4. What is StreamSubscription?</h3><p>When you call:</p><pre>stream.listen(...)</pre><p>Dart returns a:</p><pre>StreamSubscription</pre><p>Example:</p><pre>StreamSubscription&lt;int&gt; subscription =<br>    numberStream().listen((value) {<br>  print(value);<br>});</pre><p>The subscription represents your <strong>active connection to the Stream</strong>.</p><p>It allows you to control that connection.</p><p>For example:</p><pre>subscription.pause();</pre><p>Pause receiving events.</p><pre>subscription.resume();</pre><p>Resume receiving events.</p><p>And:</p><pre>subscription.cancel();</pre><p>Stop listening to the Stream completely.</p><h3>5. Why Do We Need StreamSubscription?</h3><p>This is especially important in Flutter.</p><p>Imagine you are listening to a Stream inside a screen.</p><pre>class HomeScreen extends StatefulWidget {<br>  const HomeScreen({super.key});</pre><pre>  @override<br>  State&lt;HomeScreen&gt; createState() =&gt; _HomeScreenState();<br>}</pre><pre>class _HomeScreenState extends State&lt;HomeScreen&gt; {</pre><pre>  @override<br>  void initState() {<br>    super.initState();</pre><pre>    numberStream().listen((value) {<br>      print(value);<br>    });<br>  }<br>}</pre><p>What happens when the screen is removed?</p><p>The Stream may still be active.</p><p>If the Stream is something like:</p><ul><li>WebSocket</li><li>Location updates</li><li>Firebase listener</li><li>Connectivity listener</li><li>Sensor data</li></ul><p>it could continue producing events.</p><p>That’s why we should keep the subscription and cancel it when we’re done.</p><pre>late StreamSubscription&lt;int&gt; subscription;</pre><p>Then:</p><pre>@override<br>void initState() {<br>  super.initState();</pre><pre>  subscription = numberStream().listen((value) {<br>    print(value);<br>  });<br>}</pre><p>And finally:</p><pre>@override<br>void dispose() {<br>  subscription.cancel();<br>  super.dispose();<br>}</pre><p>This is a very important Flutter pattern.</p><h3>6. StreamSubscription Lifecycle</h3><p>A typical lifecycle looks like this:</p><pre>Create Stream<br>      │<br>      ▼<br>   listen()<br>      │<br>      ▼<br>StreamSubscription<br>      │<br>      ├──── pause()<br>      │<br>      ├──── resume()<br>      │<br>      └──── cancel()<br>               │<br>               ▼<br>          Stop listening</pre><h3>7. Handling Errors</h3><p>Streams can also produce errors.</p><p>You can handle them using onError.</p><pre>final subscription = stream.listen(<br>  (data) {<br>    print(&quot;Data: $data&quot;);<br>  },<br>  onError: (error) {<br>    print(&quot;Error: $error&quot;);<br>  },<br>);</pre><p>You can also handle when the Stream finishes:</p><pre>final subscription = stream.listen(<br>  (data) {<br>    print(data);<br>  },<br>  onDone: () {<br>    print(&quot;Stream completed&quot;);<br>  },<br>);</pre><h3>8. StreamController</h3><p>Another important concept is StreamController.</p><p>It allows us to manually add events to a Stream.</p><pre>final controller = StreamController&lt;int&gt;();</pre><p>Now we can listen:</p><pre>controller.stream.listen((value) {<br>  print(&quot;Received: $value&quot;);<br>});</pre><p>And send values:</p><pre>controller.add(10);<br>controller.add(20);<br>controller.add(30);</pre><p>The listener receives:</p><pre>Received: 10<br>Received: 20<br>Received: 30</pre><p>When we’re completely done:</p><pre>controller.close();</pre><h3>9. Real-World Example: Connectivity</h3><p>One of the most common uses of Streams in Flutter is monitoring network connectivity.</p><p>For example:</p><pre>final subscription = connectivityStream.listen(<br>  (status) {<br>    if (status == ConnectivityStatus.connected) {<br>      print(&quot;Internet connected&quot;);<br>    } else {<br>      print(&quot;Internet disconnected&quot;);<br>    }<br>  },<br>);</pre><p>The application can react whenever connectivity changes.</p><p>This can be useful for:</p><pre>Internet Connected<br>       ↓<br>Sync pending data</pre><pre>Internet Disconnected<br>       ↓<br>Show offline UI</pre><h3>10. Real-World Example: WebSocket</h3><p>Streams are extremely useful for real-time communication.</p><p>For example, WebSockets provide a continuous flow of messages.</p><pre>final socket = WebSocket.connect(<br>  Uri.parse(&quot;wss://example.com&quot;),<br>);</pre><p>The incoming messages can be consumed as a Stream.</p><p>Conceptually:</p><pre>Server<br>   │<br>   ├── Message 1<br>   ├── Message 2<br>   ├── Message 3<br>   └── Message 4<br>          │<br>          ▼<br>       Stream<br>          │<br>          ▼<br>       listen()</pre><p>This is useful for:</p><ul><li>Chat applications</li><li>Live notifications</li><li>Stock prices</li><li>Live scores</li><li>Multiplayer games</li><li>Real-time dashboards</li></ul><h3>11. Streams with Firebase</h3><p>Firebase provides many APIs that expose Streams.</p><p>For example:</p><pre>FirebaseAuth.instance.authStateChanges()</pre><p>returns a Stream.</p><p>We can listen to it:</p><pre>final subscription =<br>    FirebaseAuth.instance.authStateChanges().listen(<br>  (user) {<br>    if (user != null) {<br>      print(&quot;User logged in&quot;);<br>    } else {<br>      print(&quot;User logged out&quot;);<br>    }<br>  },<br>);</pre><p>Whenever authentication state changes, we receive a new event.</p><h3>12. Streams in BLoC Architecture</h3><p>Streams become even more interesting when working with <strong>BLoC</strong>.</p><p>BLoC stands for:</p><p><strong>Business Logic Component</strong></p><p>The basic idea is:</p><pre>UI<br> │<br> │ Event<br> ▼<br>BLoC<br> │<br> │ State<br> ▼<br>UI</pre><p>BLoC commonly uses Streams internally to manage events and states.</p><p>For example:</p><pre>abstract class CounterEvent {}</pre><pre>class IncrementEvent extends CounterEvent {}</pre><p>The BLoC receives events:</p><pre>on&lt;IncrementEvent&gt;((event, emit) {<br>  emit(CounterState());<br>});</pre><p>The UI reacts to state changes.</p><p>With the flutter_bloc package, much of the Stream management is handled for you.</p><p>For example:</p><pre>BlocBuilder&lt;CounterBloc, CounterState&gt;(<br>  builder: (context, state) {<br>    return Text(<br>      state.counter.toString(),<br>    );<br>  },<br>);</pre><p>You don’t usually need to manually call listen() for simple UI rebuilding.</p><p>However, BlocListener is useful when you need to react to a state change with a side effect.</p><pre>BlocListener&lt;LoginBloc, LoginState&gt;(<br>  listener: (context, state) {<br>    if (state is LoginSuccess) {<br>      Navigator.pushNamed(context, &#39;/home&#39;);<br>    }<br>  },<br>  child: LoginScreen(),<br>);</pre><h3>13. listen() vs StreamBuilder</h3><p>This is a very common question.</p><h3>listen()</h3><p>Use listen() when you want to <strong>perform an action</strong> when data arrives.</p><p>Example:</p><pre>stream.listen((value) {<br>  print(value);<br>});</pre><p>Typical use cases:</p><ul><li>Trigger navigation</li><li>Show a SnackBar</li><li>Log something</li><li>Call another method</li><li>Perform side effects</li></ul><h3>StreamBuilder</h3><p>Use StreamBuilder when the Stream&#39;s data should <strong>update your UI</strong>.</p><p>Example:</p><pre>StreamBuilder&lt;int&gt;(<br>  stream: numberStream(),<br>  builder: (context, snapshot) {<br>    if (!snapshot.hasData) {<br>      return const CircularProgressIndicator();<br>    }</pre><pre>    return Text(<br>      snapshot.data.toString(),<br>    );<br>  },<br>);</pre><p>Think:</p><pre>listen()<br>    ↓<br>Perform an action<br></pre><pre>StreamBuilder<br>    ↓<br>Build/update UI</pre><h3>14. Stream vs Future</h3><p>Another important distinction is:</p><h3>Future</h3><p>A Future gives you <strong>one result</strong>.</p><pre>Future&lt;String&gt; getUser() async {<br>  return &quot;Yogesh&quot;;<br>}</pre><p>Think:</p><pre>Request<br>   ↓<br>One result</pre><h3>Stream</h3><p>A Stream can provide <strong>multiple results over time</strong>.</p><pre>Event 1<br>Event 2<br>Event 3<br>Event 4<br>...</pre><p>Therefore:</p><pre>Future → One asynchronous value</pre><pre>Stream → Multiple asynchronous values</pre><h3>15. Practical Example: Timer Stream</h3><p>Dart provides a simple way to create a periodic Stream.</p><pre>final stream = Stream.periodic(<br>  const Duration(seconds: 1),<br>  (count) =&gt; count,<br>);</pre><p>Listen to it:</p><pre>final subscription = stream.listen((count) {<br>  print(count);<br>});</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4<br>5<br>...</pre><p>Cancel it:</p><pre>subscription.cancel();</pre><p>This can be useful for:</p><ul><li>Countdown timers</li><li>Polling</li><li>Periodic updates</li><li>Refresh mechanisms</li></ul><h3>16. Important: Don’t Forget to Cancel</h3><p>One of the most common mistakes is:</p><pre>stream.listen((value) {<br>  // ...<br>});</pre><p>without keeping the subscription.</p><p>Instead:</p><pre>late StreamSubscription subscription;</pre><pre>subscription = stream.listen((value) {<br>  // ...<br>});</pre><p>Then:</p><pre>@override<br>void dispose() {<br>  subscription.cancel();<br>  super.dispose();<br>}</pre><p>This is particularly important for long-running Streams.</p><h3>17. Multiple Stream Subscriptions</h3><p>You can have multiple subscriptions.</p><pre>late StreamSubscription connectivitySubscription;<br>late StreamSubscription locationSubscription;</pre><p>Initialize:</p><pre>connectivitySubscription =<br>    connectivityStream.listen((status) {<br>  print(status);<br>});</pre><pre>locationSubscription =<br>    locationStream.listen((location) {<br>  print(location);<br>});</pre><p>Cancel both:</p><pre>@override<br>void dispose() {<br>  connectivitySubscription.cancel();<br>  locationSubscription.cancel();</pre><pre>  super.dispose();<br>}</pre><h3>18. When Should You Use Streams?</h3><p>Streams are a good choice when data can change or arrive continuously.</p><h3>Use Streams for:</h3><p><strong>Real-time data</strong></p><pre>Chat messages<br>Notifications<br>Live scores<br>Stock prices</pre><p><strong>Device data</strong></p><pre>GPS<br>Accelerometer<br>Heart rate<br>Bluetooth<br>Sensors</pre><p><strong>Application state</strong></p><pre>Authentication<br>Connectivity<br>Database changes</pre><p><strong>Continuous events</strong></p><pre>Timers<br>User events<br>WebSocket messages</pre><h3>19. When You Don’t Need a Stream</h3><p>Don’t use a Stream just because it’s available.</p><p>If you only need one asynchronous result, a Future is usually simpler.</p><p>For example:</p><pre>Future&lt;User&gt; fetchUser() async {<br>  // API call<br>}</pre><p>There is no reason to create a Stream if you’re only getting one response.</p><p>Use the right tool for the job:</p><pre>One result<br>    ↓<br>Future</pre><pre>Continuous/multiple results<br>    ↓<br>Stream</pre><h3>20. A Simple Mental Model</h3><p>The easiest way to remember all of this is:</p><pre>STREAM<br>                │<br>                │ emits events<br>                ▼<br>             listen()<br>                │<br>                ▼<br>      StreamSubscription<br>                │<br>       ┌────────┼─────────┐<br>       ▼        ▼         ▼<br>     pause    resume     cancel</pre><p>And for Flutter UI:</p><pre>Stream<br>  │<br>  ├── listen()<br>  │      ↓<br>  │   Side Effects<br>  │<br>  └── StreamBuilder<br>         ↓<br>      Update UI</pre><h3>Conclusion</h3><p>Streams are one of the most important concepts in Dart and Flutter when dealing with asynchronous data that arrives over time.</p><p>The three concepts you should remember are:</p><h3>Stream</h3><p>Produces asynchronous data over time.</p><pre>Stream&lt;int&gt;</pre><h3>listen()</h3><p>Starts listening to the Stream.</p><pre>stream.listen((data) {<br>  print(data);<br>});</pre><h3>StreamSubscription</h3><p>Gives you control over that listening process.</p><pre>final subscription = stream.listen(...);</pre><pre>subscription.pause();<br>subscription.resume();<br>subscription.cancel();</pre><p>If you’re building production Flutter applications, understanding Streams will help you work with <strong>BLoC, WebSockets, Firebase, connectivity, location, sensors, real-time APIs, and many other asynchronous systems</strong> much more confidently.</p><p>The key rule is simple:</p><blockquote><strong><em>If data keeps coming, think Stream. If you need to react to it, listen. If you need to control the listener, use StreamSubscription.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed99269fcb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OURA Ring Flutter Integration?]]></title>
            <link>https://medium.com/@yogxworld_96212/oura-ring-flutter-integration-c7bbe2ac635c?source=rss-a5a5b9b154da------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7bbe2ac635c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[oura-ring]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Yogx Technologies]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 10:34:03 GMT</pubDate>
            <atom:updated>2026-07-23T10:34:03.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Build a comprehensive health tracking app by integrating Oura Ring data using OAuth 2.0 authentication</p><h3>Introduction</h3><p>The Oura Ring has revolutionized personal health tracking by providing detailed insights into sleep, activity, readiness, and heart rate variability. For Flutter developers, integrating the Oura API opens up endless possibilities for creating personalized health and wellness applications.</p><p>In this comprehensive tutorial, I’ll walk you through the complete process of integrating Oura’s API into your Flutter application. We’ll cover the OAuth 2.0 authentication flow, automatic token management, and fetching various health metrics including daily activity, sleep patterns, readiness scores, heart rate data, and blood oxygen levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSbiXaFztR-zzOIv6_hToQ.png" /><figcaption>OURA RING INTEGRATION IN FLUTTER APP</figcaption></figure><h3>What You’ll Build</h3><p>By the end of this guide, you’ll have:</p><ul><li>A complete OAuth 2.0 authentication flow for Oura Ring</li><li>Automatic token refresh mechanism</li><li>Ability to fetch daily activity, sleep, readiness, heart rate, and SpO2 data</li><li>Clean, production-ready code with proper error handling</li><li>Secure token storage using shared preferences</li></ul><h3>Prerequisites</h3><p>Before we start, ensure you have:</p><ul><li>Flutter SDK installed (minimum version 2.0)</li><li>An Oura developer account with API credentials</li><li>Basic understanding of Flutter and Dart</li><li>A code editor (VS Code or Android Studio recommended)</li></ul><h3>Setting Up Your Oura Developer Account</h3><p>To get started with Oura API integration:</p><ol><li>Register your application on the Oura Developer Portal</li><li>Note down your Client ID and Client Secret</li><li>Configure your redirect URI (we’ll use a custom URL scheme)</li><li>Select the required scopes for your application</li></ol><p>For this tutorial, we’ll use:</p><ul><li>Client ID: Your application’s client ID</li><li>Client Secret: Your application’s client secret</li><li>Redirect URI: yourappscheme://oura-auth</li><li>Scopes: daily, heartrate, spo2</li></ul><h3>Step 1: Project Setup and Dependencies</h3><p>Start by creating a new Flutter project or adding to your existing one. Add these dependencies to your pubspec.yaml:</p><p>yaml</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_appauth: ^6.1.0<br>  http: ^1.1.0<br>  shared_preferences: ^2.2.2</pre><p>Run flutter pub get to install the dependencies.</p><h3>Platform-Specific Configuration</h3><p>Android (android/app/src/main/AndroidManifest.xml):</p><p>xml</p><pre>&lt;activity android:name=&quot;net.openid.appauth.RedirectUriReceiverActivity&quot;&gt;<br>  &lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>    &lt;data android:scheme=&quot;yourappscheme&quot; android:host=&quot;oura-auth&quot; /&gt;<br>  &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><p>iOS (ios/Runner/Info.plist):</p><p>xml</p><pre>&lt;key&gt;CFBundleURLTypes&lt;/key&gt;<br>&lt;array&gt;<br>  &lt;dict&gt;<br>    &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;<br>    &lt;array&gt;<br>      &lt;string&gt;yourappscheme&lt;/string&gt;<br>    &lt;/array&gt;<br>  &lt;/dict&gt;<br>&lt;/array&gt;</pre><h3>Step 2: Session Management with Secure Storage</h3><p>Create a SessionManager class to handle token storage and retrieval securely:</p><p>dart</p><pre>import &#39;package:shared_preferences/shared_preferences.dart&#39;;</pre><pre>class SessionManager {<br>  // Oura token keys<br>  static const String _ouraAccessTokenKey = &#39;oura_access_token&#39;;<br>  static const String _ouraRefreshTokenKey = &#39;oura_refresh_token&#39;;<br>  static const String _ouraTokenExpiryKey = &#39;oura_token_expiry&#39;;</pre><pre>  // Oura token methods<br>  static Future&lt;void&gt; setOuraAccessToken(String token) async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.setString(_ouraAccessTokenKey, token);<br>  }</pre><pre>  static Future&lt;String?&gt; getOuraAccessToken() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    return prefs.getString(_ouraAccessTokenKey);<br>  }</pre><pre>  static Future&lt;void&gt; setOuraRefreshToken(String token) async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.setString(_ouraRefreshTokenKey, token);<br>  }</pre><pre>  static Future&lt;String?&gt; getOuraRefreshToken() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    return prefs.getString(_ouraRefreshTokenKey);<br>  }</pre><pre>  static Future&lt;void&gt; setOuraTokenExpiry(DateTime expiry) async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.setString(_ouraTokenExpiryKey, expiry.toIso8601String());<br>  }</pre><pre>  static Future&lt;DateTime?&gt; getOuraTokenExpiry() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    final expiryStr = prefs.getString(_ouraTokenExpiryKey);<br>    if (expiryStr != null) {<br>      return DateTime.parse(expiryStr);<br>    }<br>    return null;<br>  }</pre><pre>  static Future&lt;void&gt; clearOuraTokens() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.remove(_ouraAccessTokenKey);<br>    await prefs.remove(_ouraRefreshTokenKey);<br>    await prefs.remove(_ouraTokenExpiryKey);<br>  }<br>}</pre><h3>Step 3: Authentication Service with OAuth 2.0</h3><p>Now, let’s implement the OAuth 2.0 authentication service for Oura:</p><p>dart</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter_appauth/flutter_appauth.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;dart:convert&#39;;</pre><pre>class OuraAuthService {<br>  static const String clientId = &#39;YOUR_CLIENT_ID&#39;;<br>  static const String clientSecret = &#39;YOUR_CLIENT_SECRET&#39;;<br>  static const String redirectUrl = &#39;yourappscheme://oura-auth&#39;;</pre><pre>  static const AuthorizationServiceConfiguration _serviceConfiguration =<br>      AuthorizationServiceConfiguration(<br>    authorizationEndpoint: &#39;https://cloud.ouraring.com/oauth/authorize&#39;,<br>    tokenEndpoint: &#39;https://api.ouraring.com/oauth/token&#39;,<br>  );</pre><pre>  // Oura scopes - choose only what you need<br>  static const List&lt;String&gt; _scopes = [<br>    &#39;daily&#39;,        // For steps, sleep, activity<br>    &#39;heartrate&#39;,    // For heart rate data<br>    &#39;spo2&#39;,         // For blood oxygen<br>  ];</pre><pre>  final FlutterAppAuth _appAuth = const FlutterAppAuth();</pre><pre>  /// Login with Oura and return access token on success<br>  Future&lt;String?&gt; login() async {<br>    try {<br>      debugPrint(&#39;Starting Oura login flow...&#39;);</pre><pre>      final AuthorizationResponse authResponse = await _appAuth.authorize(<br>        AuthorizationRequest(<br>          clientId,<br>          redirectUrl,<br>          serviceConfiguration: _serviceConfiguration,<br>          scopes: _scopes,<br>        ),<br>      );</pre><pre>      if (authResponse.authorizationCode == null) {<br>        debugPrint(&#39;User cancelled or no code received&#39;);<br>        return null;<br>      }</pre><pre>      debugPrint(&#39;Authorization Code received&#39;);</pre><pre>      // Token exchange with Basic Auth<br>      final String credentials = base64Encode(<br>        utf8.encode(&#39;$clientId:$clientSecret&#39;)<br>      );</pre><pre>      final Map&lt;String, String&gt; body = {<br>        &#39;grant_type&#39;: &#39;authorization_code&#39;,<br>        &#39;code&#39;: authResponse.authorizationCode!,<br>        &#39;redirect_uri&#39;: redirectUrl,<br>      };</pre><pre>      if (authResponse.codeVerifier != null) {<br>        body[&#39;code_verifier&#39;] = authResponse.codeVerifier!;<br>      }</pre><pre>      final http.Response tokenResponse = await http.post(<br>        Uri.parse(&#39;https://api.ouraring.com/oauth/token&#39;),<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;,<br>          &#39;Authorization&#39;: &#39;Basic $credentials&#39;,<br>        },<br>        body: body,<br>      );</pre><pre>      if (tokenResponse.statusCode == 200) {<br>        final Map&lt;String, dynamic&gt; data = jsonDecode(tokenResponse.body);<br>        final String? accessToken = data[&#39;access_token&#39;];<br>        final String? refreshToken = data[&#39;refresh_token&#39;];<br>        final int? expiresIn = data[&#39;expires_in&#39;];</pre><pre>        if (accessToken != null) {<br>          await SessionManager.setOuraAccessToken(accessToken);<br>          if (refreshToken != null) {<br>            await SessionManager.setOuraRefreshToken(refreshToken);<br>          }<br>          if (expiresIn != null) {<br>            final expiryTime = DateTime.now().add(Duration(seconds: expiresIn));<br>            await SessionManager.setOuraTokenExpiry(expiryTime);<br>          }<br>          <br>          debugPrint(&#39;Oura Login Successful!&#39;);<br>          return accessToken;<br>        }<br>      } else {<br>        debugPrint(&#39;Token Exchange Failed: ${tokenResponse.body}&#39;);<br>      }<br>      return null;<br>    } catch (e, stackTrace) {<br>      debugPrint(&#39;Oura Login Error: $e&#39;);<br>      debugPrint(&#39;Stack trace: $stackTrace&#39;);<br>      return null;<br>    }<br>  }</pre><pre>  /// Get a valid token (automatically refreshes if expired)<br>  Future&lt;String?&gt; getValidToken() async {<br>    try {<br>      final String? accessToken = await SessionManager.getOuraAccessToken();<br>      final String? refreshToken = await SessionManager.getOuraRefreshToken();<br>      final DateTime? expiryTime = await SessionManager.getOuraTokenExpiry();</pre><pre>      if (accessToken == null) {<br>        debugPrint(&#39;No Oura token found&#39;);<br>        return null;<br>      }</pre><pre>      // Check if token is expired or about to expire (within 5 minutes)<br>      final bool isExpired = expiryTime == null || <br>          DateTime.now().isAfter(expiryTime.subtract(const Duration(minutes: 5)));</pre><pre>      if (isExpired &amp;&amp; refreshToken != null) {<br>        debugPrint(&#39;Oura token expired, refreshing...&#39;);<br>        final newToken = await _refreshToken(refreshToken);<br>        if (newToken != null) {<br>          return newToken;<br>        }<br>      }</pre><pre>      return accessToken;<br>    } catch (e) {<br>      debugPrint(&#39;Error getting valid token: $e&#39;);<br>      return null;<br>    }<br>  }</pre><pre>  /// Refresh the access token using refresh token<br>  Future&lt;String?&gt; _refreshToken(String refreshToken) async {<br>    try {<br>      final String credentials = base64Encode(<br>        utf8.encode(&#39;$clientId:$clientSecret&#39;)<br>      );</pre><pre>      final http.Response response = await http.post(<br>        Uri.parse(&#39;https://api.ouraring.com/oauth/token&#39;),<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;,<br>          &#39;Authorization&#39;: &#39;Basic $credentials&#39;,<br>        },<br>        body: {<br>          &#39;grant_type&#39;: &#39;refresh_token&#39;,<br>          &#39;refresh_token&#39;: refreshToken,<br>        },<br>      );</pre><pre>      if (response.statusCode == 200) {<br>        final Map&lt;String, dynamic&gt; data = jsonDecode(response.body);<br>        final String? newAccessToken = data[&#39;access_token&#39;];<br>        final String? newRefreshToken = data[&#39;refresh_token&#39;];<br>        final int? expiresIn = data[&#39;expires_in&#39;];</pre><pre>        if (newAccessToken != null) {<br>          await SessionManager.setOuraAccessToken(newAccessToken);<br>          <br>          if (newRefreshToken != null) {<br>            await SessionManager.setOuraRefreshToken(newRefreshToken);<br>          }<br>          <br>          if (expiresIn != null) {<br>            final expiryTime = DateTime.now().add(Duration(seconds: expiresIn));<br>            await SessionManager.setOuraTokenExpiry(expiryTime);<br>          }<br>          <br>          debugPrint(&#39;Token refreshed successfully&#39;);<br>          return newAccessToken;<br>        }<br>      } else {<br>        debugPrint(&#39;Refresh failed: ${response.body}&#39;);<br>        await SessionManager.clearOuraTokens();<br>      }<br>      return null;<br>    } catch (e) {<br>      debugPrint(&#39;Error refreshing token: $e&#39;);<br>      return null;<br>    }<br>  }</pre><pre>  Future&lt;bool&gt; isConnected() async {<br>    final token = await getValidToken();<br>    return token != null;<br>  }</pre><pre>  Future&lt;void&gt; logout() async {<br>    await SessionManager.clearOuraTokens();<br>    debugPrint(&#39;Oura logout complete&#39;);<br>  }<br>}</pre><h3>Step 4: API Service for Fetching Health Data</h3><p>Create the API service that will interact with Oura’s endpoints:</p><p>dart</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;</pre><pre>class OuraApiService {<br>  static const String _baseUrl = &#39;https://api.ouraring.com/v2/usercollection&#39;;</pre><pre>  final String token;</pre><pre>  OuraApiService(this.token);</pre><pre>  Map&lt;String, String&gt; get _headers =&gt; {<br>    &#39;Authorization&#39;: &#39;Bearer $token&#39;,<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  };</pre><pre>  static String _dateStr(DateTime d) =&gt; <br>    &#39;${d.year.toString().padLeft(4, &#39;0&#39;)}-&#39;<br>    &#39;${d.month.toString().padLeft(2, &#39;0&#39;)}-&#39;<br>    &#39;${d.day.toString().padLeft(2, &#39;0&#39;)}&#39;;</pre><pre>  static String _isoStr(DateTime d) =&gt; <br>    d.toUtc().toIso8601String().replaceAll(RegExp(r&#39;\.\d+Z$&#39;), &#39;Z&#39;);</pre><pre>  // ── API Methods with better error handling ──────────────────────────────</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getDailyActivity({DateTime? date}) async {<br>    final targetDate = _dateStr(date ?? DateTime.now());<br>    return _get(&#39;daily_activity&#39;, {<br>      &#39;start_date&#39;: targetDate,<br>      &#39;end_date&#39;: targetDate,<br>    });<br>  }</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getDailySleep({DateTime? date}) async {<br>    final targetDate = _dateStr(date ?? DateTime.now());<br>    return _get(&#39;daily_sleep&#39;, {<br>      &#39;start_date&#39;: targetDate,<br>      &#39;end_date&#39;: targetDate,<br>    });<br>  }</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getDailyReadiness({DateTime? date}) async {<br>    final targetDate = _dateStr(date ?? DateTime.now());<br>    return _get(&#39;daily_readiness&#39;, {<br>      &#39;start_date&#39;: targetDate,<br>      &#39;end_date&#39;: targetDate,<br>    });<br>  }</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getHeartRate({<br>    Duration duration = const Duration(hours: 24),<br>  }) async {<br>    final now = DateTime.now().toUtc();<br>    final start = _isoStr(now.subtract(duration));<br>    final end = _isoStr(now);<br>    return _get(&#39;heartrate&#39;, {<br>      &#39;start_datetime&#39;: start,<br>      &#39;end_datetime&#39;: end,<br>    });<br>  }</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getDailySpo2({DateTime? date}) async {<br>    final targetDate = _dateStr(date ?? DateTime.now());<br>    return _get(&#39;daily_spo2&#39;, {<br>      &#39;start_date&#39;: targetDate,<br>      &#39;end_date&#39;: targetDate,<br>    });<br>  }</pre><pre>  // ── Private Helper with better error handling ────────────────────────────</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; _get(<br>    String path, [<br>    Map&lt;String, String&gt;? params,<br>  ]) async {<br>    final uri = Uri.parse(&#39;$_baseUrl/$path&#39;).replace(<br>      queryParameters: params,<br>    );</pre><pre>    debugPrint(&#39;Oura API Request: ${uri.toString()}&#39;);</pre><pre>    try {<br>      final response = await http.get(uri, headers: _headers);</pre><pre>      debugPrint(&#39;Oura API Response Status: ${response.statusCode}&#39;);</pre><pre>      if (response.statusCode == 200) {<br>        return jsonDecode(response.body) as Map&lt;String, dynamic&gt;;<br>      } else if (response.statusCode == 401) {<br>        // Authentication error - throw to trigger refresh<br>        throw HttpException(<br>          &#39;Unauthorized: ${response.body}&#39;,<br>          uri: uri,<br>          statusCode: response.statusCode,<br>        );<br>      } else {<br>        // For other errors, return empty data structure<br>        debugPrint(&#39;Oura API Error (${response.statusCode}): ${response.body}&#39;);<br>        return {&#39;data&#39;: []};<br>      }<br>    } catch (e) {<br>      if (e is HttpException) rethrow;<br>      debugPrint(&#39;Oura API Exception: $e&#39;);<br>      return {&#39;data&#39;: []};<br>    }<br>  }<br>}</pre><pre>class HttpException implements Exception {<br>  final String message;<br>  final Uri? uri;<br>  final int? statusCode;<br>  <br>  HttpException(this.message, {this.uri, this.statusCode});<br>  <br>  @override<br>  String toString() =&gt; message;<br>}</pre><h3>Step 5: Building the User Interface</h3><p>Now, let’s create a comprehensive UI to display Oura health data:</p><p>dart</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>class OuraDataScreen extends StatefulWidget {<br>  @override<br>  _OuraDataScreenState createState() =&gt; _OuraDataScreenState();<br>}</pre><pre>class _OuraDataScreenState extends State&lt;OuraDataScreen&gt; {<br>  final OuraAuthService _authService = OuraAuthService();<br>  <br>  Map&lt;String, dynamic&gt;? _activityData;<br>  Map&lt;String, dynamic&gt;? _sleepData;<br>  Map&lt;String, dynamic&gt;? _readinessData;<br>  Map&lt;String, dynamic&gt;? _heartRateData;<br>  Map&lt;String, dynamic&gt;? _spo2Data;<br>  <br>  bool _isLoading = false;<br>  String? _errorMessage;<br>  String? _selectedDate;</pre><pre>  @override<br>  void initState() {<br>    super.initState();<br>    _selectedDate = DateTime.now().toIso8601String().split(&#39;T&#39;)[0];<br>    _checkConnection();<br>  }</pre><pre>  Future&lt;void&gt; _checkConnection() async {<br>    final isConnected = await _authService.isConnected();<br>    if (isConnected) {<br>      _fetchData();<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Oura Ring Data&#39;),<br>        actions: [<br>          IconButton(<br>            icon: Icon(Icons.refresh),<br>            onPressed: _fetchData,<br>          ),<br>          IconButton(<br>            icon: Icon(Icons.logout),<br>            onPressed: _handleLogout,<br>          ),<br>        ],<br>      ),<br>      body: _buildBody(),<br>    );<br>  }</pre><pre>  Widget _buildBody() {<br>    if (_isLoading) {<br>      return Center(child: CircularProgressIndicator());<br>    }</pre><pre>    if (_errorMessage != null) {<br>      return Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Icon(Icons.error, size: 64, color: Colors.red),<br>            SizedBox(height: 16),<br>            Text(<br>              _errorMessage!,<br>              textAlign: TextAlign.center,<br>              style: TextStyle(fontSize: 16),<br>            ),<br>            SizedBox(height: 16),<br>            ElevatedButton(<br>              onPressed: _handleLogin,<br>              child: Text(&#39;Login with Oura&#39;),<br>            ),<br>          ],<br>        ),<br>      );<br>    }</pre><pre>    if (_activityData == null) {<br>      return Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Icon(Icons.health_and_safety, size: 64, color: Colors.blue),<br>            SizedBox(height: 16),<br>            Text(<br>              &#39;Connect your Oura Ring to start tracking&#39;,<br>              style: TextStyle(fontSize: 16),<br>            ),<br>            SizedBox(height: 16),<br>            ElevatedButton(<br>              onPressed: _handleLogin,<br>              child: Text(&#39;Connect Oura Ring&#39;),<br>            ),<br>          ],<br>        ),<br>      );<br>    }</pre><pre>    return SingleChildScrollView(<br>      padding: EdgeInsets.all(16),<br>      child: Column(<br>        children: [<br>          _buildDateSelector(),<br>          SizedBox(height: 16),<br>          _buildActivityCard(),<br>          SizedBox(height: 16),<br>          _buildSleepCard(),<br>          SizedBox(height: 16),<br>          _buildReadinessCard(),<br>          SizedBox(height: 16),<br>          _buildHeartRateCard(),<br>          SizedBox(height: 16),<br>          _buildSpo2Card(),<br>        ],<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildDateSelector() {<br>    return Row(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        IconButton(<br>          icon: Icon(Icons.arrow_back),<br>          onPressed: () =&gt; _changeDate(-1),<br>        ),<br>        Container(<br>          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),<br>          decoration: BoxDecoration(<br>            border: Border.all(color: Colors.grey),<br>            borderRadius: BorderRadius.circular(8),<br>          ),<br>          child: Text(<br>            _selectedDate ?? &#39;&#39;,<br>            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),<br>          ),<br>        ),<br>        IconButton(<br>          icon: Icon(Icons.arrow_forward),<br>          onPressed: () =&gt; _changeDate(1),<br>        ),<br>      ],<br>    );<br>  }</pre><pre>  void _changeDate(int offset) {<br>    if (_selectedDate == null) return;<br>    final date = DateTime.parse(_selectedDate!);<br>    final newDate = date.add(Duration(days: offset));<br>    setState(() {<br>      _selectedDate = newDate.toIso8601String().split(&#39;T&#39;)[0];<br>    });<br>    _fetchData();<br>  }</pre><pre>  Widget _buildActivityCard() {<br>    final activity = _activityData?[&#39;data&#39;]?[0] ?? {};<br>    return Card(<br>      elevation: 4,<br>      child: Container(<br>        padding: EdgeInsets.all(16),<br>        decoration: BoxDecoration(<br>          gradient: LinearGradient(<br>            colors: [Colors.blue.shade50, Colors.blue.shade100],<br>          ),<br>          borderRadius: BorderRadius.circular(8),<br>        ),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Row(<br>              children: [<br>                Icon(Icons.directions_run, color: Colors.blue),<br>                SizedBox(width: 8),<br>                Text(<br>                  &#39;Daily Activity&#39;,<br>                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>                ),<br>              ],<br>            ),<br>            SizedBox(height: 12),<br>            _buildMetricRow(&#39;Steps&#39;, activity[&#39;steps&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Calories&#39;, activity[&#39;calories&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Active Minutes&#39;, activity[&#39;active_minutes&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Distance (km)&#39;, activity[&#39;distance&#39;]?.toString() ?? &#39;N/A&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildMetricRow(String label, String value) {<br>    return Padding(<br>      padding: EdgeInsets.symmetric(vertical: 4),<br>      child: Row(<br>        mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>        children: [<br>          Text(label, style: TextStyle(fontSize: 14)),<br>          Text(value, style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),<br>        ],<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildSleepCard() {<br>    final sleep = _sleepData?[&#39;data&#39;]?[0] ?? {};<br>    return Card(<br>      elevation: 4,<br>      child: Container(<br>        padding: EdgeInsets.all(16),<br>        decoration: BoxDecoration(<br>          gradient: LinearGradient(<br>            colors: [Colors.indigo.shade50, Colors.indigo.shade100],<br>          ),<br>          borderRadius: BorderRadius.circular(8),<br>        ),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Row(<br>              children: [<br>                Icon(Icons.bedtime, color: Colors.indigo),<br>                SizedBox(width: 8),<br>                Text(<br>                  &#39;Sleep Data&#39;,<br>                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>                ),<br>              ],<br>            ),<br>            SizedBox(height: 12),<br>            _buildMetricRow(&#39;Total Sleep&#39;, <br>              sleep[&#39;total_sleep_duration&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Deep Sleep&#39;, <br>              sleep[&#39;deep_sleep_duration&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;REM Sleep&#39;, <br>              sleep[&#39;rem_sleep_duration&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Light Sleep&#39;, <br>              sleep[&#39;light_sleep_duration&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Sleep Efficiency&#39;, <br>              sleep[&#39;efficiency&#39;]?.toString() ?? &#39;N/A&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildReadinessCard() {<br>    final readiness = _readinessData?[&#39;data&#39;]?[0] ?? {};<br>    return Card(<br>      elevation: 4,<br>      child: Container(<br>        padding: EdgeInsets.all(16),<br>        decoration: BoxDecoration(<br>          gradient: LinearGradient(<br>            colors: [Colors.green.shade50, Colors.green.shade100],<br>          ),<br>          borderRadius: BorderRadius.circular(8),<br>        ),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Row(<br>              children: [<br>                Icon(Icons.energy_savings_leaf, color: Colors.green),<br>                SizedBox(width: 8),<br>                Text(<br>                  &#39;Readiness Score&#39;,<br>                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>                ),<br>              ],<br>            ),<br>            SizedBox(height: 12),<br>            _buildMetricRow(&#39;Readiness Score&#39;, <br>              readiness[&#39;score&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Resting HR&#39;, <br>              readiness[&#39;resting_heart_rate&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;HRV Balance&#39;, <br>              readiness[&#39;hrv_balance&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Recovery Index&#39;, <br>              readiness[&#39;recovery_index&#39;]?.toString() ?? &#39;N/A&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildHeartRateCard() {<br>    final heartRateData = _heartRateData?[&#39;data&#39;] ?? [];<br>    if (heartRateData.isEmpty) {<br>      return Card(<br>        child: Padding(<br>          padding: EdgeInsets.all(16),<br>          child: Text(&#39;No heart rate data available&#39;),<br>        ),<br>      );<br>    }</pre><pre>    final latest = heartRateData.last;<br>    return Card(<br>      elevation: 4,<br>      child: Container(<br>        padding: EdgeInsets.all(16),<br>        decoration: BoxDecoration(<br>          gradient: LinearGradient(<br>            colors: [Colors.red.shade50, Colors.red.shade100],<br>          ),<br>          borderRadius: BorderRadius.circular(8),<br>        ),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Row(<br>              children: [<br>                Icon(Icons.favorite, color: Colors.red),<br>                SizedBox(width: 8),<br>                Text(<br>                  &#39;Heart Rate&#39;,<br>                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>                ),<br>              ],<br>            ),<br>            SizedBox(height: 12),<br>            Text(<br>              &#39;${latest[&#39;bpm&#39;] ?? &#39;N/A&#39;} BPM&#39;,<br>              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),<br>            ),<br>            SizedBox(height: 8),<br>            Text(&#39;Time: ${latest[&#39;timestamp&#39;] ?? &#39;N/A&#39;}&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildSpo2Card() {<br>    final spo2Data = _spo2Data?[&#39;data&#39;]?[0] ?? {};<br>    return Card(<br>      elevation: 4,<br>      child: Container(<br>        padding: EdgeInsets.all(16),<br>        decoration: BoxDecoration(<br>          gradient: LinearGradient(<br>            colors: [Colors.purple.shade50, Colors.purple.shade100],<br>          ),<br>          borderRadius: BorderRadius.circular(8),<br>        ),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Row(<br>              children: [<br>                Icon(Icons.bloodtype, color: Colors.purple),<br>                SizedBox(width: 8),<br>                Text(<br>                  &#39;Blood Oxygen (SpO2)&#39;,<br>                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>                ),<br>              ],<br>            ),<br>            SizedBox(height: 12),<br>            _buildMetricRow(&#39;Average SpO2&#39;, <br>              spo2Data[&#39;avg_spo2&#39;]?.toString() ?? &#39;N/A&#39;),<br>            _buildMetricRow(&#39;Minimum SpO2&#39;, <br>              spo2Data[&#39;min_spo2&#39;]?.toString() ?? &#39;N/A&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Future&lt;void&gt; _handleLogin() async {<br>    setState(() {<br>      _isLoading = true;<br>      _errorMessage = null;<br>    });</pre><pre>    try {<br>      final token = await _authService.login();<br>      if (token != null) {<br>        await _fetchData();<br>      } else {<br>        setState(() {<br>          _errorMessage = &#39;Login failed. Please try again.&#39;;<br>          _isLoading = false;<br>        });<br>      }<br>    } catch (e) {<br>      setState(() {<br>        _errorMessage = &#39;An error occurred: $e&#39;;<br>        _isLoading = false;<br>      });<br>    }<br>  }</pre><pre>  Future&lt;void&gt; _handleLogout() async {<br>    await _authService.logout();<br>    setState(() {<br>      _activityData = null;<br>      _sleepData = null;<br>      _readinessData = null;<br>      _heartRateData = null;<br>      _spo2Data = null;<br>    });<br>  }</pre><pre>  Future&lt;void&gt; _fetchData() async {<br>    setState(() {<br>      _isLoading = true;<br>      _errorMessage = null;<br>    });</pre><pre>    try {<br>      final token = await _authService.getValidToken();<br>      if (token == null) {<br>        setState(() {<br>          _errorMessage = &#39;Please login again&#39;;<br>          _isLoading = false;<br>        });<br>        return;<br>      }</pre><pre>      final apiService = OuraApiService(token);<br>      final date = DateTime.parse(_selectedDate!);</pre><pre>      final activity = await apiService.getDailyActivity(date: date);<br>      final sleep = await apiService.getDailySleep(date: date);<br>      final readiness = await apiService.getDailyReadiness(date: date);<br>      final heartRate = await apiService.getHeartRate();<br>      final spo2 = await apiService.getDailySpo2(date: date);</pre><pre>      setState(() {<br>        _activityData = activity;<br>        _sleepData = sleep;<br>        _readinessData = readiness;<br>        _heartRateData = heartRate;<br>        _spo2Data = spo2;<br>        _isLoading = false;<br>      });<br>    } catch (e) {<br>      setState(() {<br>        _errorMessage = &#39;Failed to fetch data: $e&#39;;<br>        _isLoading = false;<br>      });<br>    }<br>  }<br>}</pre><h3>Step 6: Main Application Integration</h3><p>Update your main application file to include the Oura data screen:</p><p>dart</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Oura Ring Integration&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>        useMaterial3: true,<br>      ),<br>      home: OuraDataScreen(),<br>    );<br>  }<br>}</pre><h3>Understanding Oura API Data Structure</h3><h3>Daily Activity Response</h3><p>json</p><pre>{<br>  &quot;data&quot;: [{<br>    &quot;day&quot;: &quot;2024-01-15&quot;,<br>    &quot;steps&quot;: 10000,<br>    &quot;calories&quot;: 2500,<br>    &quot;active_minutes&quot;: 60,<br>    &quot;distance&quot;: 8.5<br>  }]<br>}</pre><h3>Daily Sleep Response</h3><p>json</p><pre>{<br>  &quot;data&quot;: [{<br>    &quot;day&quot;: &quot;2024-01-15&quot;,<br>    &quot;total_sleep_duration&quot;: 480,<br>    &quot;deep_sleep_duration&quot;: 120,<br>    &quot;rem_sleep_duration&quot;: 90,<br>    &quot;light_sleep_duration&quot;: 270,<br>    &quot;efficiency&quot;: 85<br>  }]<br>}</pre><h3>Daily Readiness Response</h3><p>json</p><pre>{<br>  &quot;data&quot;: [{<br>    &quot;day&quot;: &quot;2024-01-15&quot;,<br>    &quot;score&quot;: 80,<br>    &quot;resting_heart_rate&quot;: 55,<br>    &quot;hrv_balance&quot;: 65,<br>    &quot;recovery_index&quot;: 70<br>  }]<br>}</pre><h3>Best Practices and Optimization Tips</h3><h3>1. Token Management</h3><ul><li>Store tokens securely using encrypted shared preferences</li><li>Implement automatic token refresh 5 minutes before expiry</li><li>Clear tokens on logout or authentication failure</li></ul><h3>2. Error Handling</h3><ul><li>Implement retry logic for network failures</li><li>Provide user-friendly error messages</li><li>Log errors for debugging purposes</li></ul><h3>3. Performance Optimization</h3><ul><li>Cache data locally to reduce API calls</li><li>Implement pagination for historical data</li><li>Use FutureBuilder for async data loading</li></ul><h3>4. User Experience</h3><ul><li>Show loading indicators during data fetch</li><li>Implement pull-to-refresh functionality</li><li>Provide offline data access where possible</li></ul><h3>5. Security Considerations</h3><ul><li>Never hardcode client secrets in client-side code</li><li>Use environment variables for sensitive credentials</li><li>Implement proper scope permissions</li></ul><h3>Testing Your Integration</h3><h3>Unit Testing</h3><p>dart</p><pre>void main() {<br>  group(&#39;OuraAuthService&#39;, () {<br>    test(&#39;login returns token on success&#39;, () async {<br>      // Mock HTTP client and test login flow<br>    });<br>  });<br>}</pre><h3>Integration Testing</h3><ol><li>Test the complete OAuth flow</li><li>Verify token refresh mechanism</li><li>Test API calls with different parameters</li><li>Validate error handling scenarios</li></ol><h3>Common Issues and Solutions</h3><p>Issue: Redirect URI not working<br>Solution: Verify the URL scheme is registered in both Android and iOS manifests.</p><p>Issue: Token refresh fails<br>Solution: Ensure the refresh token is stored correctly and hasn’t expired. Check if the client secret is correct.</p><p>Issue: API returns 403 error<br>Solution: Verify that the user has granted the required scopes. The user may need to re-authorize for additional permissions.</p><p>Issue: Missing data for a specific date<br>Solution: The user may not have worn the ring on that day. Check if there’s any data available for the date range.</p><h3>Extending Your Integration</h3><h3>Additional API Endpoints</h3><ul><li>Workout data</li><li>Sleep timeline</li><li>Trend data for long-term analysis</li><li>User profile information</li></ul><h3>Advanced Features</h3><ul><li>Real-time data streaming</li><li>Health insights and recommendations</li><li>Data visualization with charts</li><li>Integration with other health apps</li></ul><h3>Conclusion</h3><p>Integrating the Oura Ring API into your Flutter app provides users with valuable insights into their health and wellness journey. With proper OAuth 2.0 authentication and token management, you can create a seamless experience that combines Oura’s powerful health tracking with your application’s unique features.</p><p>The complete authentication and API service code we’ve built provides a solid foundation for any health tracking application. You can extend this by adding more data endpoints, implementing data visualization, or even creating personalized health insights based on the user’s Oura data.</p><h3>Key Takeaways</h3><ul><li>OAuth 2.0 authentication is essential for secure API access</li><li>Automatic token refresh ensures uninterrupted data access</li><li>Proper error handling improves user experience</li><li>Clean separation of concerns makes code maintainable</li><li>Comprehensive UI provides clear data visualization</li></ul><p><em>This guide was written for Flutter 3.0+ and the latest Oura API v2. Always check for API updates and deprecations when building production applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7bbe2ac635c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WHOOP in Flutter?]]></title>
            <link>https://medium.com/@yogxworld_96212/whoop-in-flutter-a9c353965380?source=rss-a5a5b9b154da------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9c353965380</guid>
            <category><![CDATA[whoops]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[connect]]></category>
            <dc:creator><![CDATA[Yogx Technologies]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 10:17:26 GMT</pubDate>
            <atom:updated>2026-07-23T10:17:26.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Build a powerful health tracking app by integrating WHOOP wearable data using OAuth 2.0 authentication</p><h3>Introduction</h3><p>The WHOOP wearable device has become increasingly popular among fitness enthusiasts and athletes for its advanced physiological tracking capabilities. As a Flutter developer, integrating WHOOP’s API into your app can provide users with valuable insights into their recovery, sleep patterns, and overall health metrics.</p><p>In this comprehensive guide, I’ll walk you through the complete process of integrating WHOOP’s developer API into your Flutter application. We’ll cover OAuth 2.0 authentication, token management, and making API calls to fetch real user data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4rI4aekZi7dIsS9PvrqVw.png" /><figcaption>Connect Whoop in Flutter App</figcaption></figure><h3>What You’ll Build</h3><p>By the end of this tutorial, you’ll have:</p><ul><li>A fully functional OAuth 2.0 authentication flow with WHOOP</li><li>Automatic token refresh mechanism</li><li>Ability to fetch recovery scores, sleep data, and cycle information</li><li>Clean, maintainable code structure using best practices</li></ul><h3>Prerequisites</h3><p>Before we start, make sure you have:</p><ul><li>Flutter SDK installed (minimum version 2.0)</li><li>A WHOOP developer account with API credentials</li><li>Basic understanding of Flutter and Dart</li><li>A code editor (VS Code or Android Studio)</li></ul><h3>Setting Up Your WHOOP Developer Account</h3><p>First, you’ll need to register your application with WHOOP:</p><ol><li>Visit the WHOOP Developer Portal</li><li>Create a new application</li><li>Note down your Client ID and Client Secret</li><li>Configure your redirect URI (we’ll use a custom URL scheme)</li></ol><p>For this tutorial, we’ll use:</p><ul><li>Client ID: Your application’s client ID</li><li>Client Secret: Your application’s client secret</li><li>Redirect URI: yourappscheme://whoop-auth</li></ul><h3>Step 1: Project Setup and Dependencies</h3><p>Create a new Flutter project or add to your existing one. Add these dependencies to your pubspec.yaml:</p><p>yaml</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_appauth: ^6.1.0<br>  http: ^1.1.0<br>  shared_preferences: ^2.2.2</pre><p>Run flutter pub get to install the dependencies.</p><h3>Platform-Specific Configuration</h3><p>Android (android/app/src/main/AndroidManifest.xml):</p><p>xml</p><pre>&lt;activity android:name=&quot;net.openid.appauth.RedirectUriReceiverActivity&quot;&gt;<br>  &lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>    &lt;data android:scheme=&quot;yourappscheme&quot; android:host=&quot;whoop-auth&quot; /&gt;<br>  &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><p>iOS (ios/Runner/Info.plist):</p><p>xml</p><pre>&lt;key&gt;CFBundleURLTypes&lt;/key&gt;<br>&lt;array&gt;<br>  &lt;dict&gt;<br>    &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;<br>    &lt;array&gt;<br>      &lt;string&gt;yourappscheme&lt;/string&gt;<br>    &lt;/array&gt;<br>  &lt;/dict&gt;<br>&lt;/array&gt;</pre><h3>Step 2: Session Management</h3><p>We need a central place to store and retrieve authentication tokens. Create a SessionManager class:</p><p>dart</p><pre>import &#39;package:shared_preferences/shared_preferences.dart&#39;;</pre><pre>class SessionManager {<br>  static const String _whoopAccessTokenKey = &#39;whoop_access_token&#39;;<br>  static const String _whoopRefreshTokenKey = &#39;whoop_refresh_token&#39;;<br>  static const String _whoopTokenExpiryKey = &#39;whoop_token_expiry&#39;;</pre><pre>  static Future&lt;void&gt; setWhoopAccessToken(String token) async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.setString(_whoopAccessTokenKey, token);<br>  }</pre><pre>  static String? getWhoopAccessToken() {<br>    final prefs = SharedPreferences.getInstance();<br>    return prefs.getString(_whoopAccessTokenKey);<br>  }</pre><pre>  static Future&lt;void&gt; setWhoopRefreshToken(String token) async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.setString(_whoopRefreshTokenKey, token);<br>  }</pre><pre>  static String? getWhoopRefreshToken() {<br>    final prefs = SharedPreferences.getInstance();<br>    return prefs.getString(_whoopRefreshTokenKey);<br>  }</pre><pre>  static Future&lt;void&gt; setWhoopTokenExpiry(DateTime expiry) async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.setString(_whoopTokenExpiryKey, expiry.toIso8601String());<br>  }</pre><pre>  static Future&lt;DateTime?&gt; getWhoopTokenExpiry() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    final expiryStr = prefs.getString(_whoopTokenExpiryKey);<br>    if (expiryStr != null) {<br>      return DateTime.parse(expiryStr);<br>    }<br>    return null;<br>  }</pre><pre>  static Future&lt;void&gt; clearWhoopTokens() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    await prefs.remove(_whoopAccessTokenKey);<br>    await prefs.remove(_whoopRefreshTokenKey);<br>    await prefs.remove(_whoopTokenExpiryKey);<br>  }<br>}</pre><h3>Step 3: Authentication Service</h3><p>Now, let’s implement the OAuth 2.0 authentication service. This handles the login flow and token refresh.</p><p>dart</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter_appauth/flutter_appauth.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;dart:convert&#39;;</pre><pre>class WhoopAuthService {<br>  static const String clientId = &#39;YOUR_CLIENT_ID&#39;;<br>  static const String redirectUrl = &#39;yourappscheme://whoop-auth&#39;;<br>  static const String clientSecret = &#39;YOUR_CLIENT_SECRET&#39;;</pre><pre>  static const AuthorizationServiceConfiguration _serviceConfiguration =<br>      AuthorizationServiceConfiguration(<br>    authorizationEndpoint: &#39;https://api.prod.whoop.com/oauth/oauth2/auth&#39;,<br>    tokenEndpoint: &#39;https://api.prod.whoop.com/oauth/oauth2/token&#39;,<br>  );</pre><pre>  static const List&lt;String&gt; _scopes = [<br>    &#39;read:recovery&#39;,<br>    &#39;read:cycles&#39;,<br>    &#39;read:sleep&#39;,<br>    &#39;read:workout&#39;,<br>    &#39;read:profile&#39;,<br>    &#39;read:body_measurement&#39;,<br>    &#39;offline&#39;,<br>  ];</pre><pre>  final FlutterAppAuth _appAuth = const FlutterAppAuth();</pre><pre>  Future&lt;String?&gt; login() async {<br>    try {<br>      final AuthorizationResponse authResponse = await _appAuth.authorize(<br>        AuthorizationRequest(<br>          clientId,<br>          redirectUrl,<br>          serviceConfiguration: _serviceConfiguration,<br>          scopes: _scopes,<br>        ),<br>      );</pre><pre>      if (authResponse.authorizationCode == null) {<br>        debugPrint(&#39;Authorization code request failed&#39;);<br>        return null;<br>      }</pre><pre>      final http.Response tokenResponse = await http.post(<br>        Uri.parse(&#39;https://api.prod.whoop.com/oauth/oauth2/token&#39;),<br>        headers: {&#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;},<br>        body: {<br>          &#39;grant_type&#39;: &#39;authorization_code&#39;,<br>          &#39;code&#39;: authResponse.authorizationCode!,<br>          &#39;redirect_uri&#39;: redirectUrl,<br>          &#39;client_id&#39;: clientId,<br>          &#39;client_secret&#39;: clientSecret,<br>        },<br>      );</pre><pre>      if (tokenResponse.statusCode == 200) {<br>        final Map&lt;String, dynamic&gt; data = jsonDecode(tokenResponse.body);<br>        final String? accessToken = data[&#39;access_token&#39;];<br>        final String? refreshToken = data[&#39;refresh_token&#39;];<br>        final int? expiresIn = data[&#39;expires_in&#39;];</pre><pre>        if (accessToken != null) {<br>          await SessionManager.setWhoopAccessToken(accessToken);<br>          if (refreshToken != null) {<br>            await SessionManager.setWhoopRefreshToken(refreshToken);<br>          }<br>          if (expiresIn != null) {<br>            await SessionManager.setWhoopTokenExpiry(<br>              DateTime.now().add(Duration(seconds: expiresIn)),<br>            );<br>          }<br>          return accessToken;<br>        }<br>      }<br>      return null;<br>    } catch (e) {<br>      debugPrint(&#39;Login error: $e&#39;);<br>      return null;<br>    }<br>  }</pre><pre>  Future&lt;String?&gt; refreshToken() async {<br>    try {<br>      final String? refreshToken = SessionManager.getWhoopRefreshToken();</pre><pre>      if (refreshToken == null) {<br>        await SessionManager.clearWhoopTokens();<br>        return null;<br>      }</pre><pre>      final http.Response tokenResponse = await http.post(<br>        Uri.parse(&#39;https://api.prod.whoop.com/oauth/oauth2/token&#39;),<br>        headers: {&#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;},<br>        body: {<br>          &#39;grant_type&#39;: &#39;refresh_token&#39;,<br>          &#39;refresh_token&#39;: refreshToken,<br>          &#39;client_id&#39;: clientId,<br>          &#39;client_secret&#39;: clientSecret,<br>        },<br>      );</pre><pre>      if (tokenResponse.statusCode == 200) {<br>        final Map&lt;String, dynamic&gt; data = jsonDecode(tokenResponse.body);<br>        final String? newAccessToken = data[&#39;access_token&#39;];<br>        final String? newRefreshToken = data[&#39;refresh_token&#39;];<br>        final int? expiresIn = data[&#39;expires_in&#39;];</pre><pre>        if (newAccessToken != null) {<br>          await SessionManager.setWhoopAccessToken(newAccessToken);<br>          if (newRefreshToken != null) {<br>            await SessionManager.setWhoopRefreshToken(newRefreshToken);<br>          }<br>          if (expiresIn != null) {<br>            await SessionManager.setWhoopTokenExpiry(<br>              DateTime.now().add(Duration(seconds: expiresIn)),<br>            );<br>          }<br>          return newAccessToken;<br>        }<br>      }<br>      await SessionManager.clearWhoopTokens();<br>      return null;<br>    } catch (e) {<br>      debugPrint(&#39;Refresh token error: $e&#39;);<br>      return null;<br>    }<br>  }</pre><pre>  Future&lt;String?&gt; getValidToken() async {<br>    try {<br>      final String? accessToken = SessionManager.getWhoopAccessToken();<br>      final DateTime? expiry = await SessionManager.getWhoopTokenExpiry();<br>      <br>      if (accessToken == null || expiry == null || DateTime.now().isAfter(expiry)) {<br>        return await refreshToken();<br>      }<br>      return accessToken;<br>    } catch (e) {<br>      debugPrint(&#39;Error getting valid token: $e&#39;);<br>      return null;<br>    }<br>  }<br>}</pre><h3>Step 4: API Service for Data Fetching</h3><p>Now, let’s create the service that will interact with WHOOP’s developer API endpoints:</p><p>dart</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;</pre><pre>class WhoopApiService {<br>  static const String _baseUrl = &#39;https://api.prod.whoop.com/developer/v2&#39;;</pre><pre>  Map&lt;String, String&gt; _headers(String token) =&gt; {<br>    &#39;Authorization&#39;: &#39;Bearer $token&#39;,<br>  };</pre><pre>  static String _iso(DateTime d) =&gt;<br>      d.toUtc().toIso8601String().replaceAll(RegExp(r&#39;\.\d+&#39;), &#39;&#39;);</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getCycles() {<br>    final now = DateTime.now();<br>    final start = _iso(now.subtract(const Duration(hours: 24)));<br>    final end = _iso(now);<br>    return _get(&#39;cycle&#39;, {&#39;start&#39;: start, &#39;end&#39;: end});<br>  }</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getRecovery() {<br>    final now = DateTime.now();<br>    final start = _iso(now.subtract(const Duration(hours: 24)));<br>    final end = _iso(now);<br>    return _get(&#39;recovery&#39;, {&#39;start&#39;: start, &#39;end&#39;: end});<br>  }</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; getSleep() {<br>    final now = DateTime.now();<br>    final start = _iso(now.subtract(const Duration(hours: 24)));<br>    final end = _iso(now);<br>    return _get(&#39;activity/sleep&#39;, {&#39;start&#39;: start, &#39;end&#39;: end});<br>  }</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; _get(<br>    String path, [<br>    Map&lt;String, String&gt;? params,<br>  ]) async {<br>    try {<br>      final uri = Uri.parse(&#39;$_baseUrl/$path&#39;).replace(queryParameters: params);</pre><pre>      String? accessToken = SessionManager.getWhoopAccessToken();</pre><pre>      if (accessToken == null) {<br>        throw Exception(&#39;Access token not found&#39;);<br>      }</pre><pre>      http.Response response = await http.get(<br>        uri,<br>        headers: _headers(accessToken),<br>      );</pre><pre>      if (response.statusCode == 401) {<br>        final newToken = await WhoopAuthService().refreshToken();<br>        if (newToken == null) {<br>          throw Exception(&#39;Token refresh failed&#39;);<br>        }<br>        response = await http.get(uri, headers: _headers(newToken));<br>      }</pre><pre>      if (response.statusCode != 200) {<br>        throw Exception(<br>          &#39;API error: ${response.statusCode} - ${response.body}&#39;,<br>        );<br>      }</pre><pre>      return jsonDecode(response.body) as Map&lt;String, dynamic&gt;;<br>    } catch (e) {<br>      debugPrint(&#39;API call error: $e&#39;);<br>      rethrow;<br>    }<br>  }<br>}</pre><h3>Step 5: Building the User Interface</h3><p>Create a simple UI to display the fetched data:</p><p>dart</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>class WhoopDataScreen extends StatefulWidget {<br>  @override<br>  _WhoopDataScreenState createState() =&gt; _WhoopDataScreenState();<br>}</pre><pre>class _WhoopDataScreenState extends State&lt;WhoopDataScreen&gt; {<br>  final WhoopAuthService _authService = WhoopAuthService();<br>  final WhoopApiService _apiService = WhoopApiService();<br>  <br>  Map&lt;String, dynamic&gt;? _recoveryData;<br>  Map&lt;String, dynamic&gt;? _sleepData;<br>  Map&lt;String, dynamic&gt;? _cycleData;<br>  bool _isLoading = false;<br>  String? _errorMessage;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;WHOOP Data&#39;),<br>        actions: [<br>          IconButton(<br>            icon: Icon(Icons.refresh),<br>            onPressed: _fetchData,<br>          ),<br>        ],<br>      ),<br>      body: _buildBody(),<br>    );<br>  }</pre><pre>  Widget _buildBody() {<br>    if (_isLoading) {<br>      return Center(child: CircularProgressIndicator());<br>    }</pre><pre>    if (_errorMessage != null) {<br>      return Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Icon(Icons.error, size: 64, color: Colors.red),<br>            SizedBox(height: 16),<br>            Text(_errorMessage!),<br>            SizedBox(height: 16),<br>            ElevatedButton(<br>              onPressed: _handleLogin,<br>              child: Text(&#39;Login with WHOOP&#39;),<br>            ),<br>          ],<br>        ),<br>      );<br>    }</pre><pre>    if (_recoveryData == null) {<br>      return Center(<br>        child: ElevatedButton(<br>          onPressed: _handleLogin,<br>          child: Text(&#39;Connect WHOOP&#39;),<br>        ),<br>      );<br>    }</pre><pre>    return ListView(<br>      padding: EdgeInsets.all(16),<br>      children: [<br>        _buildRecoveryCard(),<br>        SizedBox(height: 16),<br>        _buildSleepCard(),<br>        SizedBox(height: 16),<br>        _buildCycleCard(),<br>      ],<br>    );<br>  }</pre><pre>  Widget _buildRecoveryCard() {<br>    final recovery = _recoveryData?[&#39;recovery&#39;]?[0] ?? {};<br>    return Card(<br>      child: Padding(<br>        padding: EdgeInsets.all(16),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Text(<br>              &#39;Recovery Score&#39;,<br>              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>            ),<br>            SizedBox(height: 8),<br>            Text(<br>              &#39;${recovery[&#39;score&#39;]?[&#39;recovery_score&#39;] ?? &#39;N/A&#39;}%&#39;,<br>              style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),<br>            ),<br>            SizedBox(height: 8),<br>            Text(&#39;Status: ${recovery[&#39;score&#39;]?[&#39;recovery_status&#39;] ?? &#39;N/A&#39;}&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildSleepCard() {<br>    final sleep = _sleepData?[&#39;sleep&#39;]?[0] ?? {};<br>    return Card(<br>      child: Padding(<br>        padding: EdgeInsets.all(16),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Text(<br>              &#39;Sleep Data&#39;,<br>              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>            ),<br>            SizedBox(height: 8),<br>            Text(&#39;Duration: ${sleep[&#39;sleep_duration&#39;] ?? &#39;N/A&#39;} minutes&#39;),<br>            Text(&#39;Efficiency: ${sleep[&#39;efficiency&#39;] ?? &#39;N/A&#39;}%&#39;),<br>            Text(&#39;Deep Sleep: ${sleep[&#39;deep_sleep_duration&#39;] ?? &#39;N/A&#39;} minutes&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Widget _buildCycleCard() {<br>    final cycle = _cycleData?[&#39;cycles&#39;]?[0] ?? {};<br>    return Card(<br>      child: Padding(<br>        padding: EdgeInsets.all(16),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            Text(<br>              &#39;Physiological Cycle&#39;,<br>              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),<br>            ),<br>            SizedBox(height: 8),<br>            Text(&#39;Strain: ${cycle[&#39;score&#39;]?[&#39;strain&#39;] ?? &#39;N/A&#39;}&#39;),<br>            Text(&#39;Max HR: ${cycle[&#39;score&#39;]?[&#39;max_heart_rate&#39;] ?? &#39;N/A&#39;} bpm&#39;),<br>            Text(&#39;Avg HR: ${cycle[&#39;score&#39;]?[&#39;avg_heart_rate&#39;] ?? &#39;N/A&#39;} bpm&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  Future&lt;void&gt; _handleLogin() async {<br>    setState(() {<br>      _isLoading = true;<br>      _errorMessage = null;<br>    });</pre><pre>    try {<br>      final token = await _authService.login();<br>      if (token != null) {<br>        await _fetchData();<br>      } else {<br>        setState(() {<br>          _errorMessage = &#39;Login failed. Please try again.&#39;;<br>          _isLoading = false;<br>        });<br>      }<br>    } catch (e) {<br>      setState(() {<br>        _errorMessage = &#39;An error occurred: $e&#39;;<br>        _isLoading = false;<br>      });<br>    }<br>  }</pre><pre>  Future&lt;void&gt; _fetchData() async {<br>    setState(() {<br>      _isLoading = true;<br>      _errorMessage = null;<br>    });</pre><pre>    try {<br>      final token = await _authService.getValidToken();<br>      if (token == null) {<br>        setState(() {<br>          _errorMessage = &#39;Please login again&#39;;<br>          _isLoading = false;<br>        });<br>        return;<br>      }</pre><pre>      final recovery = await _apiService.getRecovery();<br>      final sleep = await _apiService.getSleep();<br>      final cycles = await _apiService.getCycles();</pre><pre>      setState(() {<br>        _recoveryData = recovery;<br>        _sleepData = sleep;<br>        _cycleData = cycles;<br>        _isLoading = false;<br>      });<br>    } catch (e) {<br>      setState(() {<br>        _errorMessage = &#39;Failed to fetch data: $e&#39;;<br>        _isLoading = false;<br>      });<br>    }<br>  }<br>}</pre><h3>Step 6: Main Application Integration</h3><p>Update your main app file to include the WHOOP data screen:</p><p>dart</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;WHOOP Integration Demo&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: WhoopDataScreen(),<br>    );<br>  }<br>}</pre><h3>Understanding the Data Flow</h3><p>Let’s break down how the integration works:</p><ol><li>Authentication Flow: When the user taps “Connect WHOOP”, the app launches the WHOOP authorization page. The user logs in and grants permissions. WHOOP redirects back to your app with an authorization code.</li><li>Token Exchange: The app exchanges the authorization code for access and refresh tokens. These tokens are stored securely using shared preferences.</li><li>Making API Calls: For each API request, the app uses the access token. If the token has expired (401 status code), it automatically refreshes using the refresh token.</li><li>Data Display: The fetched data is parsed and displayed in a user-friendly format.</li></ol><h3>Error Handling and Best Practices</h3><h3>Token Management</h3><ul><li>Always check token expiry before making API calls</li><li>Implement automatic token refresh</li><li>Clear tokens when they’re invalid</li></ul><h3>User Experience</h3><ul><li>Show loading indicators during network operations</li><li>Provide clear error messages</li><li>Implement retry mechanisms for failed requests</li></ul><h3>Security</h3><ul><li>Never hardcode client secrets in client-side code</li><li>Use secure storage for tokens</li><li>Implement proper scope permissions</li></ul><h3>Testing Your Integration</h3><p>To test your integration:</p><ol><li>Run the app on a physical device or emulator</li><li>Tap “Connect WHOOP”</li><li>Complete the authorization flow</li><li>Verify that data appears on the screen</li><li>Test the refresh mechanism by waiting for the token to expire</li></ol><h3>Common Issues and Solutions</h3><p>Issue: Redirect URI doesn’t work<br>Solution: Ensure the URL scheme is properly configured in both Android and iOS manifests.</p><p>Issue: Token refresh fails<br>Solution: Verify that your app has offline access scope. Check that the refresh token is stored correctly.</p><p>Issue: API returns 401 errors<br>Solution: Implement the automatic refresh logic as shown in the code above.</p><h3>Conclusion</h3><p>Integrating WHOOP API into your Flutter app opens up a world of possibilities for health and fitness applications. With OAuth 2.0 authentication and proper token management, you can provide users with seamless access to their physiological data.</p><p>The code we’ve built together provides a solid foundation that you can extend with additional features like:</p><ul><li>Historical data visualization</li><li>Workout tracking</li><li>User profile management</li><li>Data synchronization across devices</li></ul><p>Remember to always respect user privacy and handle health data responsibly. Happy coding!</p><h3>Resources for Further Learning</h3><ul><li>WHOOP Developer Documentation</li><li>Flutter OAuth 2.0 Best Practices</li><li>Health Data Privacy Guidelines</li><li>Flutter State Management Patterns</li></ul><p><em>This guide was written for Flutter 3.0+ and the latest WHOOP API v2. Always check for API updates and deprecations when building production applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9c353965380" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>