我正在开发一个 flutter 应用程序,用于列出我的手机并将其连接到应用程序内的其他设备。所以我使用的是 flutter_bluetooth_serial 包。我实现了与文档中几乎相同的代码,但在应用程序的初始化状态中调用 startDiscovery() 函数后,应用程序会无缘无故地立即调用 cancelDiscovery。代码成功运行了前两三次,但之后开始产生以下错误
D/BluetoothAdapter(15019): startDiscovery(): called by: com.example.bluetooth_app
D/FlutterBluePlugin(15019): Canceling discovery (stream closed)
D/BluetoothAdapter(15019): cancelDiscovery(): called by: com.example.bluetooth_app
不知道发生了什么。我正在使用 flutter 3.7 和软件包版本 0.4.0[最新]
这是完整应用程序的代码 -
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
class FooPage extends StatefulWidget {
const FooPage({super.key});
@override
State<FooPage> createState() => _FooPageState();
}
class _FooPageState extends State<FooPage> {
List<BluetoothDiscoveryResult> devices = [];
late StreamSubscription<BluetoothDiscoveryResult>
_discoveryStreamSubscription;
@override
void initState() {
super.initState();
_startDiscovery();
}
void _startDiscovery() {
_discoveryStreamSubscription =
FlutterBluetoothSerial.instance.startDiscovery().listen(
(r) {
print('device found');
bool deviceFound = false;
devices.forEach((element) {
if (element.device.address == r.device.address) {
deviceFound = true;
}
});
if (!deviceFound) {
setState(() {
devices.add(r);
});
}
},
);
_discoveryStreamSubscription.onDone(() {
setState(() {
print('stream closed');
// _isDiscovering = false;
});
});
}
@override
Widget build(BuildContext context) {
print(devices);
return Scaffold(
appBar: AppBar(
title: Text("Bluetooth Devices"),
),
body: devices.length == 0
? Center(
child: Text('No Nearby devices can be found currently...'),
)
: ListView(
children: devices
.map(
(e) => ListTile(
title: Text(e.device.name!),
subtitle: Text(e.device.type.stringValue),
),
)
.toList(),
),
);
}
}
在开始之前
FlutterBluetoothSerial.instance.startDiscovery()
,
您需要先使用 FlutterBluetoothSerial.instance.cancelDiscovery()
取消它。
这解决了我的问题