用 flutter 使用flutter_blue写一个domo
时间: 2023-10-12 15:05:12 浏览: 162
flutter_blue:Flutter的蓝牙插件
好的,下面是简单的 Flutter Blue demo:
首先需要在 `pubspec.yaml` 中添加依赖:
```yaml
dependencies:
flutter_blue: ^0.7.3
```
然后在代码中导入 `flutter_blue`:
```dart
import 'package:flutter_blue/flutter_blue.dart';
```
接下来,我们可以创建一个 `BluetoothManager` 类来管理蓝牙扫描和连接:
```dart
class BluetoothManager {
FlutterBlue flutterBlue = FlutterBlue.instance;
StreamSubscription<ScanResult> _scanSubscription;
BluetoothDevice _connectedDevice;
Future<bool> scanForDevices() async {
try {
_scanSubscription = flutterBlue.scan().listen((scanResult) {
print('Found device: ${scanResult.device.name}');
});
return true;
} catch (e) {
print(e.toString());
return false;
}
}
Future<bool> connectToDevice(String deviceId) async {
try {
var device = await flutterBlue.connect(deviceId);
_connectedDevice = device;
return true;
} catch (e) {
print(e.toString());
return false;
}
}
void disconnectFromDevice() {
if (_connectedDevice != null) {
_connectedDevice.disconnect();
_connectedDevice = null;
}
}
void stopScan() {
_scanSubscription?.cancel();
_scanSubscription = null;
}
}
```
此时,我们就可以在 UI 中使用上述方法了。例如,我们可以创建一个 `ScanButton`,当用户点击按钮时开始扫描:
```dart
class ScanButton extends StatefulWidget {
@override
_ScanButtonState createState() => _ScanButtonState();
}
class _ScanButtonState extends State<ScanButton> {
bool isScanning = false;
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text(isScanning ? 'Stop scan' : 'Start scan'),
onPressed: () async {
if (isScanning) {
BluetoothManager().stopScan();
} else {
BluetoothManager().scanForDevices();
}
setState(() {
isScanning = !isScanning;
});
},
);
}
}
```
我们也可以创建一个 `ConnectButton`,当用户点击按钮时连接到设备:
```dart
class ConnectButton extends StatefulWidget {
final String deviceId;
ConnectButton({this.deviceId});
@override
_ConnectButtonState createState() => _ConnectButtonState();
}
class _ConnectButtonState extends State<ConnectButton> {
bool isConnected = false;
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text(isConnected ? 'Disconnect' : 'Connect'),
onPressed: () async {
if (isConnected) {
BluetoothManager().disconnectFromDevice();
} else {
BluetoothManager().connectToDevice(widget.deviceId);
}
setState(() {
isConnected = !isConnected;
});
},
);
}
}
```
最后,我们可以在 UI 中使用这两个按钮:
```dart
class BluetoothDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Bluetooth Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ScanButton(),
SizedBox(height: 16),
ConnectButton(deviceId: 'device-id-here'),
],
),
),
);
}
}
```
请注意,这只是一个简单的 demo,并没有处理错误处理和连接状态更新等问题。
阅读全文