Flutter蓝牙通信插件smartble_sdk的使用
概述
smartble_sdk
是一个用于 Flutter 的蓝牙通信插件。它支持 Android 和 iOS 平台,并允许开发者轻松实现蓝牙设备的扫描、连接和数据传输功能。
使用步骤
1. 添加依赖
在 pubspec.yaml
文件中添加 smartble_sdk
依赖:
dependencies:
smartble_sdk: ^1.0.0
运行以下命令以安装依赖:
flutter pub get
2. 初始化插件
在项目中创建一个状态管理类来初始化和操作 SmartbleSdk
。
示例代码
import 'package:flutter/material.dart';
import 'package:smartble_sdk/smartble_sdk.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final smartble = SmartbleSdk();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Bluetooth Communication Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
shrinkWrap: true,
children: [
// 扫描按钮
TextButton(
onPressed: () {
smartble.scan(isScan: true);
},
child: const Text("Scan"),
),
// 显示扫描结果
StreamBuilder<dynamic>(
stream: SmartbleSdk.getDeviceListStream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Container();
} else if (snapshot.connectionState == ConnectionState.active ||
snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text(
'Error',
style: TextStyle(fontSize: 16, color: Colors.black, fontWeight: FontWeight.normal),
textAlign: TextAlign.center,
);
} else if (snapshot.hasData) {
List listdata = snapshot.data ?? [];
return ListView.builder(
itemCount: listdata.length,
shrinkWrap: true,
itemBuilder: (context, i) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: InkWell(
onTap: () {
// 设置设备地址并连接
smartble.setAddress(
bname: "${listdata[i]['deviceName']}",
bmac: "${listdata[i]['deviceMacAddress']}",
);
smartble.connect();
},
child: Text(
"${listdata[i]['deviceName']} ${listdata[i]['deviceMacAddress']}",
style: const TextStyle(fontSize: 16, color: Colors.black, fontWeight: FontWeight.bold),
textAlign: TextAlign.start,
),
),
);
},
);
} else {
return const Text(
'Empty Data',
style: TextStyle(fontSize: 16, color: Colors.black, fontWeight: FontWeight.normal),
textAlign: TextAlign.center,
);
}
} else {
return Text(
'State: ${snapshot.connectionState}',
style: const TextStyle(fontSize: 16, color: Colors.black, fontWeight: FontWeight.normal),
textAlign: TextAlign.center,
);
}
},
),
],
),
),
),
);
}
}
3. 运行示例
将上述代码保存到 lib/main.dart
文件中,并运行以下命令启动应用:
flutter run
功能说明
-
扫描蓝牙设备
点击 “Scan” 按钮后,插件会开始扫描附近的蓝牙设备,并通过Stream
实时更新扫描结果。 -
选择设备并连接
在扫描结果中点击某个设备,插件会自动设置设备名称和 MAC 地址,并尝试建立连接。 -
错误处理
如果发生错误(例如未找到设备或连接失败),界面会显示错误信息。
注意事项
- 确保设备已启用蓝牙功能。
- iOS 需要配置
Info.plist
文件以请求蓝牙权限:<key>NSBluetoothAlwaysUsageDescription</key> <string>We need access to your Bluetooth to connect devices.</string>
更多关于Flutter蓝牙通信插件smartble_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙通信插件smartble_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
smartble_sdk
是一个用于 Flutter 应用的蓝牙通信插件,它提供了一些简单的 API 来帮助开发者实现与蓝牙设备的通信。以下是如何在 Flutter 项目中使用 smartble_sdk
的基本步骤。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 smartble_sdk
的依赖。
dependencies:
flutter:
sdk: flutter
smartble_sdk: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来安装依赖。
2. 导入包
在你的 Dart 文件中导入 smartble_sdk
:
import 'package:smartble_sdk/smartble_sdk.dart';
3. 初始化 SDK
在使用 SDK 之前,你需要先初始化它。
SmartBleSdk.initialize();
4. 扫描蓝牙设备
你可以使用 startScan
方法来扫描附近的蓝牙设备。
SmartBleSdk.startScan().listen((device) {
print('Found device: ${device.name}, ${device.id}');
});
5. 连接蓝牙设备
找到目标设备后,你可以使用 connect
方法来连接设备。
SmartBleSdk.connect(deviceId).then((success) {
if (success) {
print('Connected to device');
} else {
print('Failed to connect to device');
}
});
6. 发送和接收数据
连接成功后,你可以使用 sendData
方法向设备发送数据,并通过 receiveData
方法接收数据。
SmartBleSdk.sendData(deviceId, data).then((success) {
if (success) {
print('Data sent successfully');
} else {
print('Failed to send data');
}
});
SmartBleSdk.receiveData(deviceId).listen((data) {
print('Received data: $data');
});
7. 断开连接
当你不再需要与设备通信时,可以使用 disconnect
方法断开连接。
SmartBleSdk.disconnect(deviceId).then((success) {
if (success) {
print('Disconnected from device');
} else {
print('Failed to disconnect from device');
}
});
8. 处理权限
在 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>NSLocationWhenInUseUsageDescription</key>
<string>We need access to your location to scan for Bluetooth devices.</string>
9. 处理异常
在实际使用中,可能会遇到各种异常情况,例如设备未找到、连接失败等。你需要对这些情况进行处理。
try {
await SmartBleSdk.connect(deviceId);
} catch (e) {
print('Error connecting to device: $e');
}
10. 释放资源
当你的应用不再需要与蓝牙设备通信时,可以释放相关资源。
SmartBleSdk.dispose();