用 flutter 使用flutter_blue写一个读取的domo
时间: 2024-05-16 08:17:45 浏览: 11
好的,以下是一个使用 Flutter 和 flutter_blue 包读取 BLE 设备的代码示例:
首先,需要在 pubspec.yaml 文件中添加 flutter_blue 依赖:
```yaml
dependencies:
flutter:
sdk: flutter
flutter_blue: ^0.7.3
```
然后在 Dart 文件中导入 flutter_blue 包:
```dart
import 'package:flutter_blue/flutter_blue.dart';
```
接下来,我们可以创建一个 StatefulWdiget 来管理连接状态和搜索结果:
```dart
class BleDeviceScreen extends StatefulWidget {
@override
_BleDeviceScreenState createState() => _BleDeviceScreenState();
}
class _BleDeviceScreenState extends State<BleDeviceScreen> {
FlutterBlue flutterBlue = FlutterBlue.instance;
StreamSubscription<ScanResult> scanSubscription;
BluetoothDevice connectedDevice;
List<BluetoothDevice> devicesList = [];
void startScan() {
scanSubscription = flutterBlue.scan().listen((scanResult) {
if (!devicesList.contains(scanResult.device)) {
setState(() {
devicesList.add(scanResult.device);
});
}
});
}
void stopScan() {
scanSubscription?.cancel();
}
void connectToDevice(BluetoothDevice device) async {
await device.connect();
setState(() {
connectedDevice = device;
});
}
void disconnectFromDevice() async {
await connectedDevice.disconnect();
setState(() {
connectedDevice = null;
});
}
@override
void initState() {
super.initState();
startScan();
}
@override
void dispose() {
stopScan();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BLE Device'),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: devicesList.length,
itemBuilder: (BuildContext context, int index) {
BluetoothDevice device = devicesList[index];
return ListTile(
title: Text(device.name),
subtitle: Text(device.id.toString()),
trailing: connectedDevice == device
? FlatButton(
child: Text('Disconnect'),
onPressed: disconnectFromDevice,
)
: FlatButton(
child: Text('Connect'),
onPressed: () => connectToDevice(device),
),
);
},
),
),
connectedDevice != null
? StreamBuilder<List<int>>(
stream: connectedDevice.characteristic(
Guid("00002a37-0000-1000-8000-00805f9b34fb")),
builder: (BuildContext context,
AsyncSnapshot<List<int>> snapshot) {
if (snapshot.hasData) {
List<int> value = snapshot.data;
String result = String.fromCharCodes(value);
return Text('Result: $result');
} else {
return Text('No result yet');
}
},
)
: Container(),
],
),
);
}
}
```
在 initState 方法中,我们调用 startScan 方法开始扫描周围的 BLE 设备,并通过 StreamSubscription 监听扫描结果。每当扫描到一个新设备时,将其添加到 devicesList 中,并使用 setState 更新 UI。
在 ListView 中,我们将扫描到的设备显示为列表项,并提供连接和断开连接的按钮。如果设备已连接,则显示断开连接按钮。我们还为每个设备添加了一个 onTap 方法,以便在点击设备时连接到该设备。
如果已连接到设备,则会在页面底部显示一个 StreamBuilder,用于从设备读取数据。我们使用 characteristic 方法获取一个 characteristic,并使用 StreamBuilder 监听该 characteristic 的值。如果有新的值,则将其显示在页面上。
最后,我们在 dispose 方法中停止扫描并取消 StreamSubscription。
这就是一个简单的使用 Flutter 和 flutter_blue 包读取 BLE 设备的示例。