Flutter蓝牙通信插件flutter_blue_plus_windows的使用
Flutter蓝牙通信插件flutter_blue_plus_windows的使用
该项目是一个包装库,用于Flutter Blue Plus
和Win_ble
。它允许Flutter_blue_plus
在Windows上运行。
通过最小的努力,你可以在Windows上使用Flutter Blue Plus。
使用方法
你只需要更改导入语句。
// 而不是 import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
// 或者,当你导入FBP语句时可以隐藏FlutterBluePlus
import 'package:flutter_blue_plus/flutter_blue_plus.dart' hide FlutterBluePlus;
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
扫描设备
final scannedDevices = <ScanResult>{};
const timeout = Duration(seconds: 3);
FlutterBluePlus.startScan(timeout: timeout);
final sub = FlutterBluePlus.scanResults.expand((e) => e).listen(scannedDevices.add);
await Future.delayed(timeout);
sub.cancel();
scannedDevices.forEach(print);
连接设备
final scannedDevice = scannedDevices
.where((scanResult) => scanResult.device.platformName == DEVICE_NAME)
.firstOrNull;
final device = scannedDevice?.device;
device?.connect();
断开设备连接
device?.disconnect();
查看Flutter Blue Plus的使用说明,请访问Flutter Blue Plus
示例代码
以下是一个完整的示例代码,展示了如何使用flutter_blue_plus_windows
插件来扫描和连接蓝牙设备。
// Copyright 2017-2023, Charles Weinberger & Paul DeMarco.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
import 'screens/bluetooth_off_screen.dart';
import 'screens/scan_screen.dart';
void main() {
FlutterBluePlus.setLogLevel(LogLevel.verbose, color: true);
runApp(const FlutterBlueApp());
}
// 这个widget根据适配器状态显示BluetoothOffScreen或ScanScreen
class FlutterBlueApp extends StatefulWidget {
const FlutterBlueApp({Key? key}) : super(key: key);
[@override](/user/override)
State<FlutterBlueApp> createState() => _FlutterBlueAppState();
}
class _FlutterBlueAppState extends State<FlutterBlueApp> {
BluetoothAdapterState _adapterState = BluetoothAdapterState.unknown;
late StreamSubscription<BluetoothAdapterState> _adapterStateStateSubscription;
[@override](/user/override)
void initState() {
super.initState();
_adapterStateStateSubscription = FlutterBluePlus.adapterState.listen((state) {
_adapterState = state;
if (mounted) {
setState(() {});
}
});
}
[@override](/user/override)
void dispose() {
_adapterStateStateSubscription.cancel();
super.dispose();
}
[@override](/user/override)
Widget build(BuildContext context) {
Widget screen = _adapterState == BluetoothAdapterState.on
? const ScanScreen()
: BluetoothOffScreen(adapterState: _adapterState);
return MaterialApp(
color: Colors.lightBlue,
home: screen,
navigatorObservers: [BluetoothAdapterStateObserver()],
);
}
}
// 这个观察者监听蓝牙关闭并弹出当前路由
class BluetoothAdapterStateObserver extends NavigatorObserver {
StreamSubscription<BluetoothAdapterState>? _adapterStateSubscription;
[@override](/user/override)
void didPush(Route route, Route? previousRoute) {
super.didPush(route, previousRoute);
if (route.settings.name == '/DeviceScreen') {
// 开始监听蓝牙状态变化当一个新的路由被推入时
_adapterStateSubscription ??= FlutterBluePlus.adapterState.listen((state) {
if (state != BluetoothAdapterState.on) {
// 如果蓝牙关闭,则弹出当前路由
navigator?.pop();
}
});
}
}
[@override](/user/override)
void didPop(Route route, Route? previousRoute) {
super.didPop(route, previousRoute);
// 当路由被弹出时取消订阅
_adapterStateSubscription?.cancel();
_adapterStateSubscription = null;
}
}
更多关于Flutter蓝牙通信插件flutter_blue_plus_windows的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙通信插件flutter_blue_plus_windows的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_blue_plus_windows
是 flutter_blue_plus
插件的一部分,专门用于在 Windows 平台上实现蓝牙通信。flutter_blue_plus
是一个跨平台的蓝牙通信插件,支持 Android、iOS、Windows 等平台。flutter_blue_plus_windows
是其在 Windows 平台上的实现。
以下是如何在 Flutter 项目中使用 flutter_blue_plus_windows
进行蓝牙通信的基本步骤:
1. 添加依赖
在 pubspec.yaml
文件中添加 flutter_blue_plus
和 flutter_blue_plus_windows
依赖:
dependencies:
flutter:
sdk: flutter
flutter_blue_plus: ^1.8.0 # 请使用最新版本
flutter_blue_plus_windows: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
安装依赖。
2. 导入插件
在需要使用蓝牙功能的 Dart 文件中导入插件:
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
3. 初始化蓝牙适配器
在使用蓝牙功能之前,需要初始化蓝牙适配器。可以在 initState
中调用:
class BluetoothPage extends StatefulWidget {
@override
_BluetoothPageState createState() => _BluetoothPageState();
}
class _BluetoothPageState extends State<BluetoothPage> {
FlutterBluePlus flutterBlue = FlutterBluePlus.instance;
@override
void initState() {
super.initState();
initBluetooth();
}
Future<void> initBluetooth() async {
// 检查蓝牙是否可用
bool isAvailable = await flutterBlue.isAvailable;
if (!isAvailable) {
print("Bluetooth is not available on this device.");
return;
}
// 检查蓝牙是否开启
bool isOn = await flutterBlue.isOn;
if (!isOn) {
print("Bluetooth is not turned on.");
return;
}
print("Bluetooth is ready to use.");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bluetooth Example"),
),
body: Center(
child: Text("Bluetooth is ready!"),
),
);
}
}
4. 扫描蓝牙设备
使用 startScan
方法扫描附近的蓝牙设备:
void startScan() {
flutterBlue.startScan(timeout: Duration(seconds: 4));
// 监听扫描结果
flutterBlue.scanResults.listen((results) {
for (ScanResult result in results) {
print("Found device: ${result.device.name}, RSSI: ${result.rssi}");
}
});
// 监听扫描状态
flutterBlue.isScanning.listen((isScanning) {
if (isScanning) {
print("Scanning started");
} else {
print("Scanning stopped");
}
});
}
5. 连接蓝牙设备
通过扫描结果中的 BluetoothDevice
对象连接设备:
void connectToDevice(BluetoothDevice device) async {
await device.connect();
print("Connected to ${device.name}");
// 监听连接状态
device.state.listen((state) {
if (state == BluetoothDeviceState.connected) {
print("Device is connected");
} else if (state == BluetoothDeviceState.disconnected) {
print("Device is disconnected");
}
});
}
6. 发现服务和特征
连接设备后,可以发现设备的服务和特征:
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}");
}
}
}
7. 读写特征值
通过 BluetoothCharacteristic
对象读写特征值:
void readCharacteristic(BluetoothCharacteristic characteristic) async {
List<int> value = await characteristic.read();
print("Characteristic value: $value");
}
void writeCharacteristic(BluetoothCharacteristic characteristic) async {
await characteristic.write([0x12, 0x34]);
print("Characteristic value written");
}
8. 断开连接
使用 disconnect
方法断开设备连接:
void disconnectDevice(BluetoothDevice device) async {
await device.disconnect();
print("Disconnected from ${device.name}");
}