Flutter蓝牙通信插件flutterbleplugin的使用
Flutter蓝牙通信插件flutterbleplugin的使用
Flutter插件用于在Android上扫描低功耗蓝牙设备。
开始使用
此项目是Flutter的一个起点, 插件包, 它包括Android和/或iOS的平台特定实现代码。
有关Flutter开发的帮助,请查看 在线文档,其中包含教程、示例、移动开发指南和完整的API参考。
示例代码
以下是使用flutterbleplugin
插件的完整示例代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterbleplugin/flutterbleplugin.dart'; // 导入插件
// 定义BLE设备信息类
class BleInfo {
final String? name;
final String? address;
final String? rssiDistance;
final String? rssiValue;
BleInfo(this.name, this.address, this.rssiDistance, this.rssiValue);
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<BleInfo> bleInfoItems = []; // 存储扫描到的BLE设备
bool _scanning = false; // 是否正在扫描
final Flutterbleplugin _bluetooth = Flutterbleplugin(); // 初始化插件实例
@override
void initState() {
super.initState();
// 监听扫描到的设备事件
_bluetooth.devices.listen((device) {
setState(() {
// 去重处理
var list = bleInfoItems.where((i) => i.name == device.name).toList();
if (list.isEmpty) {
bleInfoItems.add(BleInfo(
device.name, device.address, device.rssiDistance, device.rssiValue));
}
});
});
// 监听扫描停止事件
_bluetooth.scanStopped.listen((device) {
setState(() {
_scanning = false;
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text(
'蓝牙设备扫描',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
child: Icon(_scanning ? Icons.stop : Icons.bluetooth_searching),
backgroundColor: Colors.green,
onPressed: () async {
try {
if (_scanning) {
// 停止扫描
await _bluetooth.stopScan();
debugPrint("扫描已停止");
setState(() {
bleInfoItems.clear(); // 清空设备列表
});
} else {
// 开始扫描
await _bluetooth.startScan(pairedDevices: false);
debugPrint("扫描已开始");
setState(() {
_scanning = true;
});
}
} on PlatformException catch (e) {
debugPrint(e.toString());
}
},
),
body: bleInfoItems.length > 0
? ListView.builder(
shrinkWrap: true,
itemCount: bleInfoItems.length,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(15),
alignment: Alignment.center,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(color: Colors.white60, blurRadius: 1.0),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
bleInfoItems[index].name!,
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
Text(
bleInfoItems[index].address!,
style: TextStyle(color: Colors.black, fontSize: 12),
),
SizedBox(height: 10),
Text(
'信号强度: ${bleInfoItems[index].rssiValue} dBm',
style: TextStyle(color: Colors.black, fontSize: 12),
),
],
),
Image.asset(
getDynamicName(
double.parse(bleInfoItems[index].rssiDistance!)),
scale: 4,
),
],
),
);
})
: Center(
child: Container(
child: Text("未发现设备"),
),
),
),
);
}
// 动态返回WiFi图标路径
getDynamicName(double rssi) {
if (rssi > 0.0 && rssi < 2.0) {
return 'assets/wifi-4.png';
} else if (rssi > 2.0 && rssi < 4.0) {
return 'assets/wifi-3.png';
} else if (rssi > 4.0 && rssi < 8.0) {
return 'assets/wifi-2.png';
} else {
return 'assets/wifi-1.png';
}
}
}
运行效果
运行上述代码后,界面将显示一个按钮用于控制扫描状态。点击按钮时,会开始或停止扫描蓝牙设备,并在列表中显示扫描到的设备信息(如名称、地址、信号强度等)。未找到设备时,界面会显示提示文字“未发现设备”。
注意事项
- 权限配置:
- 在
AndroidManifest.xml
中添加以下权限:<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- 在
更多关于Flutter蓝牙通信插件flutterbleplugin的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙通信插件flutterbleplugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,使用蓝牙进行通信通常需要借助第三方插件。flutter_blue
是一个常用的蓝牙通信插件,它提供了丰富的API来扫描、连接、读写蓝牙设备。以下是如何使用 flutter_blue
插件进行蓝牙通信的基本步骤。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 flutter_blue
依赖:
dependencies:
flutter:
sdk: flutter
flutter_blue: ^0.8.0
然后运行 flutter pub get
来安装依赖。
2. 初始化 FlutterBlue
在你的Dart文件中导入 flutter_blue
并初始化 FlutterBlue
实例:
import 'package:flutter_blue/flutter_blue.dart';
FlutterBlue flutterBlue = FlutterBlue.instance;
3. 扫描蓝牙设备
使用 startScan
方法来扫描附近的蓝牙设备:
void startScan() {
flutterBlue.startScan(timeout: Duration(seconds: 4));
flutterBlue.scanResults.listen((results) {
for (ScanResult result in results) {
print('Found device: ${result.device.name} - ${result.device.id}');
}
});
}
4. 停止扫描
使用 stopScan
方法来停止扫描:
void stopScan() {
flutterBlue.stopScan();
}
5. 连接蓝牙设备
通过 ScanResult
或 BluetoothDevice
对象来连接设备:
void connectToDevice(BluetoothDevice device) async {
await device.connect();
print('Connected to ${device.name}');
}
6. 发现服务
连接成功后,发现设备提供的服务:
void discoverServices(BluetoothDevice device) async {
List<BluetoothService> services = await device.discoverServices();
for (BluetoothService service in services) {
print('Service UUID: ${service.uuid}');
}
}
7. 读取和写入特征值
通过 BluetoothCharacteristic
对象来读取和写入特征值:
void readCharacteristic(BluetoothCharacteristic characteristic) async {
List<int> value = await characteristic.read();
print('Characteristic value: $value');
}
void writeCharacteristic(BluetoothCharacteristic characteristic, List<int> value) async {
await characteristic.write(value);
print('Characteristic value written');
}
8. 断开连接
使用 disconnect
方法来断开与设备的连接:
void disconnectDevice(BluetoothDevice device) async {
await device.disconnect();
print('Disconnected from ${device.name}');
}
9. 处理权限
在Android和iOS上,使用蓝牙需要相应的权限。确保在 AndroidManifest.xml
和 Info.plist
中添加必要的权限。
Android
在 AndroidManifest.xml
中添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
iOS
在 Info.plist
中添加以下键值对:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>We need access to Bluetooth to connect to your device.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We need access to Bluetooth to connect to your device.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need access to location to scan for Bluetooth devices.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need access to location to scan for Bluetooth devices.</string>
10. 处理状态变化
你可以监听蓝牙状态的变化,例如蓝牙是否开启:
void listenToBluetoothState() {
flutterBlue.state.listen((state) {
if (state == BluetoothState.off) {
print('Bluetooth is off');
} else if (state == BluetoothState.on) {
print('Bluetooth is on');
}
});
}
完整示例
以下是一个简单的完整示例,展示了如何扫描、连接、发现服务并读取特征值:
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: BluetoothApp(),
);
}
}
class BluetoothApp extends StatefulWidget {
[@override](/user/override)
_BluetoothAppState createState() => _BluetoothAppState();
}
class _BluetoothAppState extends State<BluetoothApp> {
FlutterBlue flutterBlue = FlutterBlue.instance;
BluetoothDevice? connectedDevice;
[@override](/user/override)
void initState() {
super.initState();
startScan();
}
void startScan() {
flutterBlue.startScan(timeout: Duration(seconds: 4));
flutterBlue.scanResults.listen((results) {
for (ScanResult result in results) {
print('Found device: ${result.device.name} - ${result.device.id}');
if (result.device.name == 'YourDeviceName') {
connectToDevice(result.device);
}
}
});
}
void connectToDevice(BluetoothDevice device) async {
await device.connect();
setState(() {
connectedDevice = device;
});
print('Connected to ${device.name}');
discoverServices(device);
}
void discoverServices(BluetoothDevice device) async {
List<BluetoothService> services = await device.discoverServices();
for (BluetoothService service in services) {
print('Service UUID: ${service.uuid}');
for (BluetoothCharacteristic characteristic in service.characteristics) {
print('Characteristic UUID: ${characteristic.uuid}');
if (characteristic.uuid.toString() == 'your-characteristic-uuid') {
readCharacteristic(characteristic);
}
}
}
}
void readCharacteristic(BluetoothCharacteristic characteristic) async {
List<int> value = await characteristic.read();
print('Characteristic value: $value');
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Bluetooth'),
),
body: Center(
child: Text(connectedDevice != null ? 'Connected to ${connectedDevice!.name}' : 'Scanning...'),
),
);
}
}