Flutter集成Spike平台插件spike_flutter_sdk的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter集成Spike平台插件spike_flutter_sdk的使用

示例代码

import 'package:flutter/material.dart';
import 'package:spike_flutter_sdk/spike_flutter_sdk.dart';

// Your API credentials
const authToken = '{YOUR_AUTH_TOKEN}';
const appId = '{YOUR_APP_ID}';
const customerEndUserId = '{YOUR_CUSTOMER_END_USER_ID}';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  SpikeConnection? _connection;
  SpikeHeartData? _lastData;

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Health Kit Api'),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Actions',
                style: TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const Divider(),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: IntrinsicHeight(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      TextButton(
                        onPressed: _createConnection,
                        child: const Text('Create connection'),
                      ),
                      const VerticalDivider(),
                      TextButton(
                        onPressed: _readData,
                        child: const Text('Read data'),
                      ),
                    ],
                  ),
                ),
              ),
              const Divider(),
              const Text(
                'Authorization data',
                style: TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const Divider(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Authorized',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(_connection != null ? 'Yes' : 'No'),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Integration user ID',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(_connection?.customerEndUserId ?? 'Not integrated, yet'),
                ],
              ),
              const Divider(),
              const Text(
                'Activity data',
                style: TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const Divider(),
              if (_lastData?.entries?.isEmpty == true)
                const Text('No heart data read.'),
              if (_lastData?.entries != null)
                ..._lastData!.entries!
                    .map((record) =&gt; _getHeartDataCard(record)),
              const Divider(),
              const Text(
                'Last send data response',
                style: TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const Divider(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _getHeartDataCard(SpikeHeartDataEntry data) {
    return Container(
      color: Colors.amber,
      margin: const EdgeInsets.all(4.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'Date',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(data.date ?? 'Unset'),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'Average HR',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(data.averageHeartRate.toString()),
            ],
          ),
        ],
      ),
    );
  }

  Future&lt;void&gt; _createConnection() async {
    _connection = await SpikeSDK.createConnection(
      appId: appId,
      authToken: authToken,
      customerEndUserId: customerEndUserId,
    );

    await _connection!.ensurePermissionsAreGranted(
      types: [SpikeDataType.heart],
    );

    setState(() {});
  }

  Future&lt;void&gt; _readData() async {
    if (_connection == null) {
      return;
    }

    final data = await _connection!.extractData(SpikeDataType.heart);
    _lastData = data;

    setState(() {});
  }
}

解释

1

  • 初始化:首先,获取正确的凭证以使用此包。在示例中,我们假设您已经获得了这些凭证。

  • 创建连接:使用收到的凭证创建连接。这可以通过以下方式完成:

    final connection = await SpikeSDK.createConnection(
      appId: appId,
      authToken: authToken,
      customerEndUserId: customerEndUserId,
    );
    
  • 请求权限:为了正确使用连接,必须首先请求所需的权限。例如,如果您想获取心率数据,则需要请求心率数据权限:

    connection.ensurePermissionsAreGrantedV2(types: [SpikeDataType.heart]);
    
  • 读取数据:使用连接读取数据。以下是两种情况的示例:

    final data = await connection.extractData(SpikeDataType.heart);
    
  • 配置背景交付(仅限WebHook连接和iOS):在您的项目“Signing & Capabilities”部分启用Background Delivery for HealthKit。在每个应用启动时调用Spike.configure()方法触发背景交付任务。将Spike初始化代码添加到ios/Runner/AppDelegate.swift文件中。代码应如下所示:

    import UIKit
    import Flutter
    import SpikeSDK
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        Spike.configure()
    
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }
    
  • 检查背景交付类型:有时您可能想要检查连接注册了哪些类型的背景交付。您可以使用以下示例接收背景交付类型的列表:

    final types = await connection.getBackgroundDeliveryTypes();
    
  • 获取Spike End User ID:使用以下代码:

    final result = await connection.getSpikeEndUserId();
    

更多关于Flutter集成Spike平台插件spike_flutter_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter集成Spike平台插件spike_flutter_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中集成并使用Spike平台插件spike_flutter_sdk的代码案例。这个示例将展示如何设置插件、初始化Spike SDK,并进行一个简单的API调用。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加spike_flutter_sdk的依赖:

dependencies:
  flutter:
    sdk: flutter
  spike_flutter_sdk: ^最新版本号  # 请替换为实际可用的最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Spike SDK

在项目的android/app/src/main/AndroidManifest.xml中,你可能需要添加一些必要的权限和配置(具体根据Spike平台的要求)。

3. 初始化Spike SDK

在你的Flutter项目中,通常会在MainActivity.kt(对于Android)或AppDelegate.swift(对于iOS)中进行一些初始化配置,但大多数情况下,Spike SDK的初始化可以在Dart代码中完成。

Dart 代码示例

import 'package:flutter/material.dart';
import 'package:spike_flutter_sdk/spike_flutter_sdk.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SpikeIntegrationExample(),
    );
  }
}

class SpikeIntegrationExample extends StatefulWidget {
  @override
  _SpikeIntegrationExampleState createState() => _SpikeIntegrationExampleState();
}

class _SpikeIntegrationExampleState extends State<SpikeIntegrationExample> {
  String result = "";

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

  void initSpikeSDK() async {
    try {
      // 替换为你的Spike平台API Key和其他必要的配置
      await SpikeFlutterSdk.init(
        apiKey: "YOUR_SPIKE_API_KEY",
        environment: "sandbox",  // 或 "production"
        // 其他可选配置
      );
      setState(() {
        result = "Spike SDK initialized successfully!";
      });
      // 调用Spike API示例
      callSpikeApi();
    } catch (e) {
      setState(() {
        result = "Spike SDK initialization failed: ${e.message}";
      });
    }
  }

  void callSpikeApi() async {
    try {
      // 示例API调用,具体API根据Spike平台文档
      var response = await SpikeFlutterSdk.someSpikeApiMethod(
        param1: "value1",
        param2: "value2",
      );
      setState(() {
        result = "API call response: ${response.toJson()}";
      });
    } catch (e) {
      setState(() {
        result = "API call failed: ${e.message}";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Spike SDK Integration Example"),
      ),
      body: Center(
        child: Text(result),
      ),
    );
  }
}

注意事项

  1. API Key:确保你使用的是Spike平台提供的有效的API Key。
  2. 环境配置:根据开发或生产环境配置environment参数。
  3. API调用:上面的callSpikeApi方法中的SpikeFlutterSdk.someSpikeApiMethod是一个示例方法,你需要根据Spike平台的实际API文档替换为正确的API调用。
  4. 错误处理:在真实应用中,请添加更多的错误处理和日志记录。

以上是一个基本的集成Spike平台插件spike_flutter_sdk的示例。请根据你具体的需求和Spike平台的文档进行详细的配置和API调用。

回到顶部