Skip to main content

rolla_sdk 0.1.15 copy "rolla_sdk: ^0.1.15" to clipboard
rolla_sdk: ^0.1.15 copied to clipboard

Rolla Health & Fitness SDK for Flutter apps — drop-in health, activity tracking, wearable band pairing, and white-label UI.

example/lib/main.dart

/// Example host app for the Rolla SDK.
///
/// Logs a user in against the Rolla rnd sandbox, initializes the SDK with the
/// returned tokens and renders `RollaSdkHome`. The complete partner-style
/// reference app is `rolla-sdk-demo-flutter`; this example stays minimal.
///
/// To run it:
/// ```
/// cd rolla-sdk/example
/// flutter run
/// ```
library;

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:rolla_sdk/rolla_sdk.dart';

/// Rolla rnd (research-and-development) sandbox. The partner ID is the shared
/// sandbox one; log in with the sandbox user Rolla issued you.
const String _apiBaseUrl = 'https://ross-rnd.rolla.cloud';
const String _partnerId = 'rollarnd_3a44409a5cb35899';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const ExampleApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Rolla SDK Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF2196F3)),
        useMaterial3: true,
      ),
      home: const LoginScreen(),
    );
  }
}

/// Tokens the SDK needs, as returned by `POST /api/login`.
class Session {
  const Session({
    required this.accessToken,
    required this.userId,
    this.refreshToken,
    this.expiresIn,
  });

  final String accessToken;
  final String? refreshToken;
  final int? expiresIn;

  /// The Rolla user ID, decoded from the access token's JWT `sub` claim.
  final String userId;
}

/// Logs in with email and password. A partner app would call its own backend
/// here instead of holding user credentials.
Future<Session> login({required String email, required String password}) async {
  final dio = Dio(BaseOptions(baseUrl: _apiBaseUrl));
  final response = await dio.post<Map<String, dynamic>>(
    '/api/login',
    data: {'email': email, 'password': password},
    options: Options(
      contentType: Headers.formUrlEncodedContentType,
      headers: {'Partner-ID': _partnerId, 'Accept': 'application/json'},
    ),
  );

  final data = response.data ?? const {};
  if (data['success'] != true) {
    throw Exception(data['reason'] as String? ?? 'Login failed');
  }
  final tokens = data['tokens'] as Map<String, dynamic>;
  final accessToken = tokens['access_token'] as String;

  return Session(
    accessToken: accessToken,
    refreshToken: tokens['refresh_token'] as String?,
    expiresIn: tokens['expires_in'] as int?,
    userId: _userIdFromJwt(accessToken),
  );
}

String _userIdFromJwt(String token) {
  final parts = token.split('.');
  final payload = utf8.decode(base64Url.decode(base64Url.normalize(parts[1])));
  return (jsonDecode(payload) as Map<String, dynamic>)['sub'] as String;
}

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _email = TextEditingController();
  final _password = TextEditingController();
  bool _busy = false;
  String? _error;

  @override
  void dispose() {
    _email.dispose();
    _password.dispose();
    super.dispose();
  }

  Future<void> _signIn() async {
    setState(() {
      _busy = true;
      _error = null;
    });
    try {
      final session = await login(email: _email.text.trim(), password: _password.text);
      if (!mounted) return;
      await Navigator.of(context).push(
        MaterialPageRoute<void>(builder: (_) => RollaScreen(session: session)),
      );
    } catch (e) {
      setState(() => _error = '$e');
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Rolla SDK Example')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
              controller: _email,
              decoration: const InputDecoration(labelText: 'Email'),
              keyboardType: TextInputType.emailAddress,
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _password,
              decoration: const InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            const SizedBox(height: 24),
            FilledButton(
              onPressed: _busy ? null : _signIn,
              child: Text(_busy ? 'Signing in…' : 'Sign in and open Rolla'),
            ),
            if (_error != null) ...[
              const SizedBox(height: 16),
              Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
            ],
          ],
        ),
      ),
    );
  }
}

/// Initializes the SDK for the signed-in user and hands the screen to it.
class RollaScreen extends StatefulWidget {
  const RollaScreen({super.key, required this.session});

  final Session session;

  @override
  State<RollaScreen> createState() => _RollaScreenState();
}

class _RollaScreenState extends State<RollaScreen> {
  bool _initialized = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _initialize();
  }

  Future<void> _initialize() async {
    final session = widget.session;
    try {
      await RollaSDK.initializeWithToken(
        accessToken: session.accessToken,
        refreshToken: session.refreshToken,
        tokenExpiresIn: session.expiresIn == null ? null : Duration(seconds: session.expiresIn!),
        userId: session.userId,
        partnerId: _partnerId,
        environment: RollaEnvironment.rnd,
        // Back button in the SDK's app bar; the SDK asks us to pop the route.
        showBackButton: true,
        onRequestDismiss: _close,
        // The user signed out inside the SDK, or the session became
        // unrecoverable: leave the SDK screen.
        onLogout: _close,
        onSessionExpired: _close,
        // The SDK could not refresh on its own. A partner app fetches a fresh
        // pair from its backend here; this example has nothing to refresh with.
        onTokenExpired: () async => null,
      );
      if (mounted) setState(() => _initialized = true);
    } catch (e) {
      if (mounted) setState(() => _error = '$e');
    }
  }

  void _close() {
    if (mounted) Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    if (_error != null) {
      return Scaffold(
        appBar: AppBar(title: const Text('Rolla')),
        body: Center(child: Text('Could not start the SDK:\n$_error', textAlign: TextAlign.center)),
      );
    }
    if (!_initialized) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }
    // RollaSdkHome owns navigation and theming from here on.
    return RollaSdkHome(userId: widget.session.userId);
  }
}