Flutter蓝牙串口BLE通信插件flutter_bluetooth_serial_ble的使用
Flutter蓝牙串口BLE通信插件flutter_bluetooth_serial_ble的使用
flutter_bluetooth_serial_ble
是一个用于Flutter应用中实现经典蓝牙(仅支持RFCOMM)和BLE通信的插件。本文将介绍如何使用该插件,并提供完整的示例代码。
插件简介
flutter_bluetooth_serial_ble
是基于 flutter_bluetooth_serial
开发的,增加了对BLE的支持。主要功能包括:
- 适配器状态监控
- 打开/关闭蓝牙
- 设备发现和配对
- 多设备连接
- 数据发送和接收
目前只支持Android平台。
使用步骤
添加依赖
在 pubspec.yaml
文件中添加插件依赖:
dependencies:
flutter_bluetooth_serial_ble: ^0.5.0
然后运行以下命令安装依赖:
flutter pub get
导入插件
在你的Dart文件中导入插件:
import 'package:flutter_bluetooth_serial_ble/flutter_bluetooth_serial_ble.dart';
示例代码
以下是一个简单的示例,展示如何使用 flutter_bluetooth_serial_ble
连接到蓝牙设备并进行数据通信。
主应用入口
import 'package:flutter/material.dart';
import './MainPage.dart';
void main() => runApp(new ExampleApplication());
class ExampleApplication extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(home: MainPage());
}
}
主页面逻辑
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial_ble/flutter_bluetooth_serial_ble.dart';
class MainPage extends StatefulWidget {
[@override](/user/override)
_MainPageState createState() => new _MainPageState();
}
class _MainPageState extends State<MainPage> {
BluetoothConnection? connection;
String address = "XX:XX:XX:XX:XX:XX"; // 替换为实际设备地址
bool isConnected = false;
[@override](/user/override)
void initState() {
super.initState();
connectToDevice();
}
Future<void> connectToDevice() async {
try {
connection = await BluetoothConnection.toAddress(address, type: BluetoothType.BLE);
print('Connected to the device');
setState(() {
isConnected = true;
});
connection!.input!.listen((Uint8List data) {
print('Data incoming: ${ascii.decode(data)}');
connection!.output.add(data); // 发送数据回显
if (ascii.decode(data).contains('!')) {
connection!.finish(); // 关闭连接
print('Disconnecting by local host');
}
}).onDone(() {
print('Disconnected by remote request');
setState(() {
isConnected = false;
});
});
} catch (exception) {
print('Cannot connect, exception occurred');
}
}
[@override](/user/override)
void dispose() {
if (connection != null && connection!.isConnected) {
connection!.finish();
}
super.dispose();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(isConnected ? 'Connected' : 'Disconnected'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: isConnected ? null : () => connectToDevice(),
child: Text('Connect'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: isConnected ? () => connection?.finish() : null,
child: Text('Disconnect'),
),
],
),
),
);
}
}
更多关于Flutter蓝牙串口BLE通信插件flutter_bluetooth_serial_ble的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙串口BLE通信插件flutter_bluetooth_serial_ble的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个使用 flutter_bluetooth_serial_ble
插件进行 Flutter 蓝牙串口通信的示例代码。这个示例展示了如何扫描蓝牙设备、连接到设备以及发送和接收数据。
首先,确保在你的 pubspec.yaml
文件中添加 flutter_bluetooth_serial_ble
依赖:
dependencies:
flutter:
sdk: flutter
flutter_bluetooth_serial_ble: ^x.y.z # 替换为最新版本号
然后,运行 flutter pub get
以获取依赖。
接下来是示例代码:
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial_ble/flutter_bluetooth_serial_ble.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
FlutterBluetoothSerial? _bluetooth;
BluetoothDevice? _connectedDevice;
bool _isScanning = false;
List<BluetoothDevice> _devices = [];
@override
void initState() {
super.initState();
initBluetooth();
}
Future<void> initBluetooth() async {
_bluetooth = FlutterBluetoothSerial.instance;
// 监听蓝牙状态变化
_bluetooth!.onStateChanged().listen((BluetoothState state) {
if (state == BluetoothState.ON) {
print("Bluetooth is ON");
} else {
print("Bluetooth is OFF");
}
});
// 获取蓝牙状态
BluetoothState state = await _bluetooth!.state;
if (state == BluetoothState.OFF) {
await _bluetooth!.turnOn();
}
}
Future<void> startScan() async {
if (_isScanning) return;
setState(() {
_isScanning = true;
_devices.clear();
});
_bluetooth!.scanResults().listen((scanResult) {
setState(() {
_devices.add(scanResult.device);
});
}).onDone(() {
setState(() {
_isScanning = false;
});
});
await _bluetooth!.startScan(allowDuplicates: false);
}
Future<void> connectToDevice(BluetoothDevice device) async {
setState(() {
_connectedDevice = device;
});
await _bluetooth!.connect(device.address);
// 监听数据接收
_bluetooth!.inputStream!.listen((Uint8List data) {
print("Received data: ${String.fromCharCodes(data)}");
});
}
Future<void> sendData(String data) async {
if (_connectedDevice == null) return;
List<int> bytesToSend = data.codeUnits;
await _bluetooth!.write(bytesToSend, _connectedDevice!.address);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Bluetooth Serial BLE Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
ElevatedButton(
onPressed: _isScanning ? null : startScan,
child: Text('Start Scanning'),
),
SizedBox(height: 16),
Expanded(
child: ListView.builder(
itemCount: _devices.length,
itemBuilder: (context, index) {
BluetoothDevice device = _devices[index];
return ListTile(
title: Text(device.name ?? 'Unknown Device'),
subtitle: Text(device.address),
trailing: IconButton(
icon: Icon(Icons.connect_without_contact),
onPressed: () => connectToDevice(device),
),
);
},
),
),
SizedBox(height: 16),
TextField(
decoration: InputDecoration(labelText: 'Send Data'),
onChanged: (value) {
// This is where you can add a button or a way to trigger sendData
},
),
SizedBox(height: 8),
ElevatedButton(
onPressed: () => sendData('Hello BLE!'),
child: Text('Send Data'),
),
],
),
),
),
);
}
}
注意事项:
-
权限:确保在 Android 和 iOS 上请求了必要的蓝牙权限。对于 Android,你可能需要在
AndroidManifest.xml
中添加权限,并在运行时请求权限。对于 iOS,你需要在Info.plist
中添加蓝牙使用描述。 -
错误处理:在实际应用中,应该添加更多的错误处理,例如处理蓝牙连接失败、扫描失败等情况。
-
UI 交互:这个示例代码仅用于演示基本的蓝牙扫描、连接和数据传输。在实际应用中,你可能需要更复杂的 UI 交互设计。
-
插件版本:确保使用最新版本的
flutter_bluetooth_serial_ble
插件,因为 API 可能会随着版本更新而变化。 -
数据格式:在实际应用中,发送和接收的数据格式需要根据你的应用需求进行定义和处理。
希望这个示例代码能帮助你理解如何使用 flutter_bluetooth_serial_ble
插件进行蓝牙串口通信。