Flutter数据保存插件save_us_starmax的使用

Flutter数据保存插件save_us_starmax的使用

save_us_starmax 是一个用于在 Flutter 应用中保存数据的插件。该插件提供了多种方法来获取和设置设备的数据,例如获取版本信息、有效历史日期、心率历史记录等。

使用指南

1. 初始化应用

首先,在 main.dart 文件中初始化应用,并加载所需的配置文件。

import 'dart:async';
import 'dart:convert';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:save_us_starmax/save_us_starmax.dart';
import 'package:save_us_starmax/save_us_starmax_platform_interface.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await dotenv.load(fileName: '.env'); // 加载环境变量配置文件
  runApp(MyApp(
    prefs: await SharedPreferences.getInstance(),
  ));
}

2. 创建主应用类

创建一个继承自 StatefulWidgetMyApp 类,并在其中定义状态管理逻辑。

class MyApp extends StatefulWidget {
  const MyApp({
    super.key,
    required this.prefs,
  });

  final SharedPreferences prefs;

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

class _MyAppState extends State<MyApp> {
  final _saveUsStarmaxPlugin = SaveUsStarmax();

  @override
  void initState() {
    super.initState();
    requestPermissionForAndroid();
    // 添加其他初始化逻辑
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin Starmax'),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 添加按钮和其他UI元素
            ],
          ),
        ),
      ),
    );
  }
}

3. 实现数据操作方法

_MyAppState 中实现与 save_us_starmax 插件相关的数据操作方法。

class _MyAppState extends State<MyApp> {
  final _saveUsStarmaxPlugin = SaveUsStarmax();

  @override
  void initState() {
    super.initState();
    requestPermissionForAndroid();
    // 初始化蓝牙扫描和连接
    FlutterBluePlus.scanResults.listen((results) {
      // 处理扫描结果
    });
    FlutterBluePlus.isScanning.listen((state) {
      // 处理扫描状态变化
    });
    FlutterBluePlus.events.onConnectionStateChanged.listen((cs) {
      // 处理连接状态变化
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin Starmax'),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextButton(
                onPressed: () async {
                  final starmaxArr = await _saveUsStarmaxPlugin.getVersion();
                  if (starmaxArr != null) {
                    _request(_devices[_index], starmaxArr);
                  }
                  setState(() => _starmaxMap['Version'] = starmaxArr);
                },
                child: RichText(
                  text: TextSpan(
                    text: 'Version',
                    style: _textStyle(),
                    children: [TextSpan(text: ' ${_starmaxMap['Version']}')],
                  ),
                ),
              ),
              // 其他按钮和操作
            ],
          ),
        ),
      ),
    );
  }

  // 定义其他方法
}

4. 请求权限

确保在 Android 设备上请求必要的权限。

Future requestPermissionForAndroid() async {
  final androidInfo = await DeviceInfoPlugin().androidInfo;

  if (kDebugMode) {
    print('androidInfo:: $androidInfo');
  }
  switch (androidInfo.version.sdkInt) {
    case > 30:
      if (!await Permission.bluetoothScan.isGranted) {
        final bluetoothScanGrant = await Permission.bluetoothScan.request().isGranted;
        if (kDebugMode) {
          print('bluetoothScanGrant:: $bluetoothScanGrant');
        }
      }
      if (!await Permission.bluetoothConnect.isGranted) {
        final bluetoothConnectGrant = await Permission.bluetoothConnect.request().isGranted;
        if (kDebugMode) {
          print('bluetoothConnectGrant:: $bluetoothConnectGrant');
        }
      }
      break;

    default:
      if (!await Permission.bluetooth.isGranted) {
        final bluetoothGrant = await Permission.bluetooth.request().isGranted;
        if (kDebugMode) {
          print('bluetoothGrant:: $bluetoothGrant');
        }
      }
      if (!await Permission.location.isGranted) {
        final locationGrant = await Permission.location.request().isGranted;
        if (kDebugMode) {
          print('locationGrant:: $locationGrant');
        }
      }
      break;
  }
}

5. 实现数据请求方法

定义一个 _request 方法用于发送数据请求并处理响应。

Future _request(BluetoothDevice device, Uint8List value) async {
  for (final s in (await device.discoverServices())
      .where((e) => e.serviceUuid == Guid(_serviceUuid))) {
    for (final c in s.characteristics.where(
        (e) => Guid(_writeCharacteristicsUuid) == e.characteristicUuid)) {
      try {
        await c.write(value);
      } catch (error) {
        if (kDebugMode) {
          print('$value:: $error');
        }
      }
    }
  }
}

6. 扫描和连接蓝牙设备

实现蓝牙设备的扫描和连接逻辑。

Future _startScan() async {
  while (SaveUsStarmaxPlatform.instance.hashCode > 0) {
    if (BluetoothConnectionState.disconnected == _connectionState) {
      await FlutterBluePlus.startScan(
        withMsd: [
          MsdFilter(
            24576,
            data: [66, 75, 45, 66, 76, 69],
          )
        ],
        timeout: const Duration(seconds: 7),
      );
    }
    await Future.delayed(const Duration(seconds: 9));
  }
}

Future _connect(BluetoothDevice device) async {
  _streamConnectionState = device.connectionState.listen(
    (BluetoothConnectionState state) async {
      if (state == BluetoothConnectionState.disconnected) {
        if (kDebugMode) {
          print("${device.disconnectReason?.code} ${device.disconnectReason?.description}");
        }
      }
      _connectionState = state;
    },
  );
  device.cancelWhenDisconnected(
    _streamConnectionState,
    delayed: true,
    next: true,
  );
  while (BluetoothConnectionState.disconnected == _connectionState) {
    try {
      await device.connect();
      if (kDebugMode) {
        print('Connected to the device successfully');
      }
      await _stopScan();
    } catch (error) {
      if (kDebugMode) {
        print('Error occurred during connection: $error');
      }
      if (error is FlutterBluePlusException) {
        switch (error.code) {
          case 133:
            if (kDebugMode) {
              print('Retrying connection...');
            }
            break;
          case 6:
            if (kDebugMode) {
              print('Device is disconnected.');
            }
            break;
        }
      } else {
        if (kDebugMode) {
          print('\x1B[31mconnecting: $error\x1B[0m');
        }
        rethrow;
      }
    } finally {
      await Future.delayed(const Duration(milliseconds: 512));
    }
  }
}

更多关于Flutter数据保存插件save_us_starmax的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据保存插件save_us_starmax的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


save_us_starmax 是一个第三方 Flutter 插件,用于在 Flutter 应用中保存数据。虽然没有找到官方的 save_us_starmax 插件,但可能是开发者为特定需求自定义的插件。如果你的插件是通过 pubspec.yaml 文件添加的,以下是如何在 Flutter 中使用它的基本步骤。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 save_us_starmax 插件的依赖项:

dependencies:
  flutter:
    sdk: flutter
  save_us_starmax: ^1.0.0  # 请检查插件的版本号

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

2. 导入插件

在你的 Dart 文件中导入插件:

import 'package:save_us_starmax/save_us_starmax.dart';

3. 使用插件

假设 save_us_starmax 插件提供了保存和读取数据的功能,以下是一个简单的示例:

class MyApp extends StatelessWidget {
  final SaveUsStarmax _saveUsStarmax = SaveUsStarmax();

  Future<void> saveData() async {
    try {
      await _saveUsStarmax.save('key', 'value');
      print('Data saved successfully');
    } catch (e) {
      print('Failed to save data: $e');
    }
  }

  Future<void> readData() async {
    try {
      String? value = await _saveUsStarmax.read('key');
      print('Data read: $value');
    } catch (e) {
      print('Failed to read data: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Save Us Starmax Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: saveData,
                child: Text('Save Data'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: readData,
                child: Text('Read Data'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
回到顶部