Flutter时间处理插件helix_timex的使用

Flutter时间处理插件helix_timex的使用

本项目是一个用于Flutter的时间处理插件包,包含针对Android和iOS平台的特定实现代码。

获取开始

对于想要开始使用Flutter的开发者,可以访问Flutter官方文档,其中提供了教程、示例、移动开发指导和完整的API参考。

示例代码

以下是一个使用helix_timex插件的完整示例代码:

import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:helix_timex/helix_timex.dart';
import 'dart:async';
import 'package:permission_handler/permission_handler.dart';

import 'location_service.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  bool isScanning = false;
  TimexConnectionState conState = TimexConnectionState.disconnected;

  HelixTimex timex = HelixTimex();

  String heartRate = '';
  String spo2 = '';
  String sis = '';
  String dis = '';
  late Timer _timer;

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

  // 平台消息异步初始化
  Future<void> initPlatformState() async {
    timex.getScanningStateStream.listen((event) {
      print('My Scanning State ' + event.toString());
      isScanning = event;
      setState(() {});
    });

    timex.getConnectionStateStream.listen((event) {
      print('My Connection State' + event.connectionState.toString());
      conState = event.connectionState!;
      setState(() {});
    });

    timex.getHeartRateStream.listen((event) {
      print('My Heart Rate' + event.toString());
      heartRate = event.toString();
      setState(() {});
    });

    timex.getSpo2Stream.listen((event) {
      print('My SpO2' + event.toString());
      spo2 = event.toString();
      setState(() {});
    });

    timex.getBloodPressureStream.listen((event) {
      print('My Blood Pressure' + event.toString());
      sis = event['sbp'].toString();
      dis = event['dbp'].toString();
      setState(() {});
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                conState == TimexConnectionState.connected ? 'Connected' :
                conState == TimexConnectionState.connecting ? 'Connecting' : 'Disconnected',
                style: TextStyle(
                  color: conState == TimexConnectionState.connected ? Colors.green : Colors.red,
                ),
              ),
              StreamBuilder<DeviceData>(
                  stream: timex.deviecFoundStream,
                  builder: (context, snapshot) {
                    return snapshot.data == null ?
                    const Text('No Device Found')
                        : Column(
                      children: [
                        Text((snapshot.data!.deviceName ?? '0').toString()),
                        Text((snapshot.data!.macAddress ?? '0').toString()),
                        TextButton(
                          onPressed: () {
                            timex.connect(macAddress: snapshot.data!.macAddress ?? '', deviceName: snapshot.data!.deviceName ?? '');
                          },
                          child: const Text('Connect'),
                        ),
                        TextButton(
                          onPressed: () {
                            timex.disConnect();
                          },
                          child: const Text('DisConnect'),
                        ),
                        TextButton(
                          onPressed: () {
                            timex.measureDynamicRate();
                          },
                          child: const Text('Measure Dynamic'),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('Heart Rate: ' + heartRate.toString()),
                            TextButton(
                              onPressed: () {
                                timex.measureHeartRate();
                              },
                              child: const Text('Measure'),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('SpO2: ' + spo2.toString()),
                            TextButton(
                              onPressed: () {
                                timex.measureSpo2();
                              },
                              child: const Text('Measure'),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Column(
                              children: [
                                Text('Sis BP: ' + sis.toString()),
                                Text('Dis BP: ' + dis.toString()),
                              ],
                            ),
                            TextButton(
                              onPressed: () {
                                timex.measureBloodPressure();
                              },
                              child: const Text('Measure'),
                            ),
                          ],
                        ),
                      ],
                    );
                  }
              ),
              const SizedBox(height: 10,),
              isScanning ?
              const CircularProgressIndicator()
                  : TextButton(
                onPressed: () async {
                  startScan();
                },
                child: const Text('Start Scan'),
              ),
              TextButton(
                onPressed: () async {
                  bool isConnected = await timex.isConnected();
                  print(isConnected);
                },
                child: const Text('See If Connected'),
              )
            ],
          ),
        ),
      ),
    );
  }

  void startScan() async {
    bool locationEnable = await LocationService().enableGPS();
    await FlutterBluetoothSerial.instance.requestEnable();
    await Permission.location.request();

    if (locationEnable) {
      bool bluetoothEnable = (await FlutterBluetoothSerial.instance.isEnabled) ?? false;

      if (bluetoothEnable) {
        if (await Permission.location.isGranted) {
          timex.startScanDevice();
        } else {
          alertToast(context, 'Location Permission is required to use this feature');
        }
      } else {
        alertToast(context, 'Please enable Bluetooth to use this feature');
      }
    } else {
      alertToast(context, 'Please enable Location to use this feature');
    }
  }
}

示例代码解释

  1. 导入必要的库:

    import 'package:flutter/material.dart';
    import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
    import 'package:helix_timex/helix_timex.dart';
    import 'dart:async';
    import 'package:permission_handler/permission_handler.dart';
    
  2. 初始化应用:

    void main() {
      runApp(const MyApp());
    }
    
  3. 定义状态管理类:

    class MyApp extends StatefulWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      bool isScanning = false;
      TimexConnectionState conState = TimexConnectionState.disconnected;
    
      HelixTimex timex = HelixTimex();
    
      String heartRate = '';
      String spo2 = '';
      String sis = '';
      String dis = '';
      late Timer _timer;
    
      @override
      void initState() {
        super.initState();
        initPlatformState();
      }
    
  4. 异步初始化平台状态:

    Future<void> initPlatformState() async {
      timex.getScanningStateStream.listen((event) {
        print('My Scanning State ' + event.toString());
        isScanning = event;
        setState(() {});
      });
    
      timex.getConnectionStateStream.listen((event) {
        print('My Connection State' + event.connectionState.toString());
        conState = event.connectionState!;
        setState(() {});
      });
    
      timex.getHeartRateStream.listen((event) {
        print('My Heart Rate' + event.toString());
        heartRate = event.toString();
        setState(() {});
      });
    
      timex.getSpo2Stream.listen((event) {
        print('My SpO2' + event.toString());
        spo2 = event.toString();
        setState(() {});
      });
    
      timex.getBloodPressureStream.listen((event) {
        print('My Blood Pressure' + event.toString());
        sis = event['sbp'].toString();
        dis = event['dbp'].toString();
        setState(() {});
      });
    }
    
  5. 构建UI:

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Plugin example app'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  conState == TimexConnectionState.connected ? 'Connected' :
                  conState == TimexConnectionState.connecting ? 'Connecting' : 'Disconnected',
                  style: TextStyle(
                    color: conState == TimexConnectionState.connected ? Colors.green : Colors.red,
                  ),
                ),
                StreamBuilder<DeviceData>(
                  stream: timex.deviecFoundStream,
                  builder: (context, snapshot) {
                    return snapshot.data == null ?
                    const Text('No Device Found')
                        : Column(
                      children: [
                        Text((snapshot.data!.deviceName ?? '0').toString()),
                        Text((snapshot.data!.macAddress ?? '0').toString()),
                        TextButton(
                          onPressed: () {
                            timex.connect(macAddress: snapshot.data!.macAddress ?? '', deviceName: snapshot.data!.deviceName ?? '');
                          },
                          child: const Text('Connect'),
                        ),
                        TextButton(
                          onPressed: () {
                            timex.disConnect();
                          },
                          child: const Text('DisConnect'),
                        ),
                        TextButton(
                          onPressed: () {
                            timex.measureDynamicRate();
                          },
                          child: const Text('Measure Dynamic'),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('Heart Rate: ' + heartRate.toString()),
                            TextButton(
                              onPressed: () {
                                timex.measureHeartRate();
                              },
                              child: const Text('Measure'),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('SpO2: ' + spo2.toString()),
                            TextButton(
                              onPressed: () {
                                timex.measureSpo2();
                              },
                              child: const Text('Measure'),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Column(
                              children: [
                                Text('Sis BP: ' + sis.toString()),
                                Text('Dis BP: ' + dis.toString()),
                              ],
                            ),
                            TextButton(
                              onPressed: () {
                                timex.measureBloodPressure();
                              },
                              child: const Text('Measure'),
                            ),
                          ],
                        ),
                      ],
                    );
                  }
                ),
                const SizedBox(height: 10,),
                isScanning ?
                const CircularProgressIndicator()
                    : TextButton(
                  onPressed: () async {
                    startScan();
                  },
                  child: const Text('Start Scan'),
                ),
                TextButton(
                  onPressed: () async {
                    bool isConnected = await timex.isConnected();
                    print(isConnected);
                  },
                  child: const Text('See If Connected'),
                )
              ],
            ),
          ),
        ),
      );
    }
    
  6. 开始扫描设备:

    void startScan() async {
      bool locationEnable = await LocationService().enableGPS();
      await FlutterBluetoothSerial.instance.requestEnable();
      await Permission.location.request();
    
      if (locationEnable) {
        bool bluetoothEnable = (await FlutterBluetoothSerial.instance.isEnabled) ?? false;
    
        if (bluetoothEnable) {
          if (await Permission.location.isGranted) {
            timex.startScanDevice();
          } else {
            alertToast(context, 'Location Permission is required to use this feature');
          }
        } else {
          alertToast(context, 'Please enable Bluetooth to use this feature');
        }
      } else {
        alertToast(context, 'Please enable Location to use this feature');
      }
    }
    

更多关于Flutter时间处理插件helix_timex的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter时间处理插件helix_timex的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


helix_timex 是一个用于 Flutter 的时间处理插件,它提供了丰富的功能来处理日期和时间。以下是如何在 Flutter 项目中使用 helix_timex 插件的基本步骤和示例。

1. 安装插件

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

dependencies:
  flutter:
    sdk: flutter
  helix_timex: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来安装插件。

2. 导入插件

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

import 'package:helix_timex/helix_timex.dart';

3. 使用插件

helix_timex 提供了多种功能来处理日期和时间。以下是一些常见的用法示例:

3.1 获取当前时间

DateTime now = HelixTimex.now();
print('当前时间: $now');

3.2 格式化时间

String formattedTime = HelixTimex.format(now, 'yyyy-MM-dd HH:mm:ss');
print('格式化后的时间: $formattedTime');

3.3 解析时间字符串

DateTime parsedTime = HelixTimex.parse('2023-10-05 14:30:00');
print('解析后的时间: $parsedTime');

3.4 时间加减

DateTime futureTime = HelixTimex.add(now, Duration(days: 7));
print('一周后的时间: $futureTime');

DateTime pastTime = HelixTimex.subtract(now, Duration(days: 7));
print('一周前的时间: $pastTime');

3.5 时间比较

bool isAfter = HelixTimex.isAfter(futureTime, now);
print('一周后的时间是否在当前时间之后: $isAfter');

bool isBefore = HelixTimex.isBefore(pastTime, now);
print('一周前的时间是否在当前时间之前: $isBefore');

3.6 计算时间差

Duration difference = HelixTimex.difference(futureTime, now);
print('时间差: $difference');

4. 其他功能

helix_timex 还提供了其他一些实用功能,比如:

  • 获取某个月的第一天和最后一天
  • 判断某一天是否是工作日或周末
  • 计算两个日期之间的工作日天数
  • 等等

你可以查阅插件的官方文档或源代码来了解更多详细的功能和用法。

5. 注意事项

  • 确保你使用的 helix_timex 版本是最新的,并且与你的 Flutter SDK 版本兼容。
  • 如果你在使用过程中遇到任何问题,可以查看插件的 GitHub 仓库或向社区寻求帮助。

6. 示例代码

以下是一个完整的示例代码,展示了如何使用 helix_timex 插件:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('HelixTimex 示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  DateTime now = HelixTimex.now();
                  print('当前时间: $now');

                  String formattedTime = HelixTimex.format(now, 'yyyy-MM-dd HH:mm:ss');
                  print('格式化后的时间: $formattedTime');

                  DateTime futureTime = HelixTimex.add(now, Duration(days: 7));
                  print('一周后的时间: $futureTime');

                  bool isAfter = HelixTimex.isAfter(futureTime, now);
                  print('一周后的时间是否在当前时间之后: $isAfter');
                },
                child: Text('测试 HelixTimex'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
回到顶部