Flutter蓝牙通信插件flutter_splendid_ble的使用

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

好的,以下是关于Flutter蓝牙通信插件flutter_splendid_ble的使用示例代码:

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

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

class SplendidBleExampleApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter BLE Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('BLE Example'),
        ),
        body: Center(
          child: StreamBuilder<BluetoothDevice>(
            stream: _splendidBleCentral.getConnectedDevices(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Text('No connected devices');
              }
              final List<ConnectedBleDevice> devices = snapshot.data!;
              return Column(
                children: devices.map((device) {
                  return ListTile(
                    title: Text(device.name),
                    subtitle: Text(device.address),
                  );
                }).toList(),
              );
            },
          ),
        ),
      ),
    );
  }

  final SplendidBleCentral _splendidBleCentral = SplendidBleCentral();
}

更多关于Flutter蓝牙通信插件flutter_splendid_ble的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蓝牙通信插件flutter_splendid_ble的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个使用Flutter蓝牙通信插件flutter_splendid_ble的简单示例代码。这个示例展示了如何扫描蓝牙设备、连接到设备以及读写特征值。

首先,确保你已经在pubspec.yaml文件中添加了flutter_splendid_ble依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_splendid_ble: ^x.y.z  # 替换为最新版本号

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

接下来是示例代码:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late BleManager _bleManager;
  late List<ScanResult> _devices;

  @override
  void initState() {
    super.initState();
    _bleManager = BleManager();
    _devices = [];
    _initializeBle();
  }

  Future<void> _initializeBle() async {
    // 初始化BLE适配器
    bool isBluetoothEnabled = await _bleManager.adapter.isEnabled();
    if (!isBluetoothEnabled) {
      bool isEnabled = await _bleManager.adapter.enable();
      if (!isEnabled) {
        // 处理蓝牙开启失败的情况
      }
    }

    // 开始扫描设备
    _bleManager.scanForDevices(
      withServices: [], // 可选,指定要扫描的服务UUID列表
      allowDuplicatesKey: false,
      scanMode: ScanMode.lowLatency,
    ).listen((scanResult) {
      setState(() {
        _devices.add(scanResult);
      });
    }).onDone(() {
      // 扫描结束回调
    }).onError((error) {
      // 处理扫描错误
    });
  }

  Future<void> _connectToDevice(ScanResult device) async {
    // 连接到设备
    BleDeviceConnection? connection = await _bleManager.connectToDevice(
      deviceId: device.device.id,
      timeout: Duration(seconds: 10),
    );

    if (connection != null) {
      // 连接成功后执行的操作
      // 示例:读取特征值
      List<Uuid> characteristicUuids = device.serviceUuids
          .map((serviceUuid) => _getServiceCharacteristicUuids(device, serviceUuid))
          .expand((list) => list)
          .toList();

      if (characteristicUuids.isNotEmpty) {
        Uuid firstCharacteristicUuid = characteristicUuids.first;
        Data? data = await connection.readCharacteristic(firstCharacteristicUuid);
        print('Read characteristic data: ${data?.toHex()}');
      }

      // 示例:写入特征值
      Uuid? writeCharacteristicUuid = characteristicUuids.isNotEmpty
          ? characteristicUuids.first
          : null;
      if (writeCharacteristicUuid != null) {
        await connection.writeCharacteristicWithoutResponse(
          writeCharacteristicUuid,
          Uint8List.fromList([0x01, 0x02, 0x03]), // 要写入的数据
        );
      }

      // 断开连接
      await connection.disconnect();
    }
  }

  List<Uuid> _getServiceCharacteristicUuids(ScanResult device, Uuid serviceUuid) {
    // 获取指定服务的特征值UUID列表(这里只是一个示例,实际需要根据设备文档获取)
    // 通常你需要根据设备的服务UUID和特征值UUID来操作
    return []; // 返回特征值UUID列表
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter BLE Example'),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount: _devices.length,
                itemBuilder: (context, index) {
                  ScanResult device = _devices[index];
                  return ListTile(
                    title: Text(device.device.name ?? 'Unknown Device'),
                    subtitle: Text(device.device.id),
                    onTap: () {
                      _connectToDevice(device);
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

注意

  1. flutter_splendid_ble插件的具体API可能会随着版本更新而变化,因此请参考最新的官方文档。
  2. 在实际项目中,你需要根据蓝牙设备的服务UUID和特征值UUID来操作,这通常可以在设备的文档中找到。
  3. 示例中的_getServiceCharacteristicUuids方法只是一个占位符,你需要根据具体设备实现它。
  4. 处理蓝牙操作时要考虑到各种可能的异常情况,例如设备连接失败、读写特征值失败等。

希望这个示例对你有所帮助!

回到顶部